This is now my current code after what user2486 said.
def romanMap():
map=((\"M\", 1000),(\"CM\", 900),(\"D\", 500),(\"CD\", 400),(\"C\", 100),(\"XC\"
def romanToInt(self, s: str) -> int:
roman_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
int_equ = 0
for i in range(len(s)):
if i > 0 and roman_dict[s[i]] > roman_dict[s[i-1]]:
int_equ += roman_dict[s[i]] - 2*roman_dict[s[i-1]]
else:
int_equ += roman_dict[s[i]]
return int_equ
try this:
def translate(string):
values = {"i":1, "v":5, "x":10, "l":50, "c":100, "m":1000}
return sum(map(lambda x: values[x], string))
The lambda stands for a one-line function. That's why they are called anonymous functions. You don't have to define them outide using def and all that formality.
You can type something like this on the shell:
f = lambda x: x + 3 f(3) 6 or f = lambda x,y: x + y f("foo", "bar") 'foobar'
Im using map to apply my new-born function into every element of a iterable. In this case, the iterable is one string like "mclvii". Doing it i generated a list where each value its his rersepective value. See a lambda example to calculate squares:
>>> a = [1,2,3,4]
>>> square = lambda x: x**2
>>> l = map(square, a)
>>> l = [1,4,9,16]
So, it's lambda when you need a function on the fly, and map when you want to apply a function to all elements in a list.
Now a example using recursion:
def translate2(string):
values = {"i":1, "v":5, "x":10, "l":50, "c":100, "m":1000}
if not string:
return 0
return values[string[0]] + translate2(string[1:])
No need to reinvent the wheel (unless you want to). Python comes with a converter:
import roman;
n=roman.fromRoman("X"); #n becomes 10
If you need it for numbers 5000 and above, you'll need to write a new function, though, and maybe make your own font to represent the lines over the roman numerals. (It will only work with some numbers, at that. Stopping at 4999 is a really good idea.)
To convert to roman numerals, use roman.toRoman(myInt)
.
Someone else actually linked to the same source code the roman module uses in one of the comments above, but I don't believe they mentioned that it actually comes with Python.
EDIT: Note that on some systems (Windows, I think) you can't just type import roman
from the default installation. However, the source code still works on Windows, and it's included with the Python 3.4.1 source code download (probably earlier ones, too) at this location /Python-3.4.1/Doc/tools/roman.py
Roman numerals are read from left to right, as you add or subtract the value of each symbol.
If a value is lower than the following value, it will be subtracted. Otherwise it will be added.
For example, we want to conver the Roman numeral MCMLIV to an Arabic number:
M = 1000 must be added, because the following letter C =100 is lower.
C = 100 must be subtracted because the following letter M =1000 is greater.
M = 1000 must be added, because the following letter L = 50 is lower.
L = 50 must be added, because the following letter I =1 is lower.
I = 1 must be subtracted, because the following letter V = 5 is greater.
V = 5 must be added, because there are no more symbols left.
We can now calculate the number:
1000 - 100 + 1000 + 50 - 1 + 5 = 1954
ref : http://www.mathinary.com/roman_numerals_from_roman_numerals_to_arabic_numbers.jsp
def from_roman(num):
roman_numerals = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
result = 0
for i,c in enumerate(num):
if (i+1) == len(num) or roman_numerals[c] >= roman_numerals[num[i+1]]:
result += roman_numerals[c]
else:
result -= roman_numerals[c]
return result
what about This piece of Code
mapping = {'I': 1, 'V': 5, 'X': 10,'L': 50, 'C': 100, 'D': 500, 'M':1000}
def roman_to_dec(roman):
"""
Convert the roman no to decimal
"""
dec = last = 0
for i in range(0, len(roman)):
no = mapping.get(roman[i])
# subtract last 2 times cuz one for this pass and another for last pass
dec = dec + (no - 2 * last) if no > last else dec + no
last = no
return dec
Okay, there are a lot of things wrong with what you currently have.
First, the reason you are getting a bunch of 0's is because you are never exiting your while string != "":
loop, and it isn't ever adding integers to the total. So total
remains zero, and keeps getting printed. I've commented the code you posted to help you understand what is going on.
def main():
string=str(input("Enter a roman numeral"))
total=0
while string != "": # Empty strings evaluate as False, this can just be 'while string:'
if string[1] == string[2] or string == len([1]): # Here you are testing the 2nd and 3rd elements.
# Also, you want to do len(string) == 1
# string will never == len([1]), so you never
# execute the code in this block.
total += string[1]+1 # You want to add the corresponding value of string[0], use a dictionary.
print (total)
# Missing the else statement in the pseudocode.
main()
user2864740 has some good comments in their posted solution, look over that to see some of the things you were doing wrong.
Here is Python (2.7 unfortunately) code that does what your given pseudocode says.
val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
def main():
string = str(raw_input('Enter a roman numeral: '))
string = string.upper()
total = 0
while string:
if len(string) == 1 or val[string[0]] >= val[string[1]]:
total += val[string[0]]
string = string[1:]
else:
total += val[string[1]] - val[string[0]]
string = string[2:]
print total
main()
Please note that the pseudocode you posted is NOT correct. Note what it will do for the input 'IIV'
. It will subtract 1 from 1, then add 5. But what it should do is subtract 2 from 5.