'This is a Roman numeral to integer program, but the output is not what i was expecting
I expect 1994
as output, but i get 1014
when the input is MCMXCIV
. Can you please give suggestions where my code went wrong. im a beginner to python, Thank you.
class Solution:
def r2int(self,s):
roman = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
s = s.replace('IV', 'IIII').replace('IX', 'V') #using replace function for exceptions
s = s.replace('XL', 'XXX').replace('XC', 'V')
s = s.replace('CD', 'V').replace('CM', 'V')
integer = 0 #this is yet to become the final value
for i in s: #taking a character
integer += roman[i] #taking value from roman and adding to integer
return integer #final integer value
Solution().r2int('MCMXCIV')
Solution 1:[1]
There is a simpler approach. Let's map each numeral to its value.
roman = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
sample = 'MCMXCIV'
converted = [roman[digit] for digit in sample]
Now converted
is [1000, 100, 1000, 10, 100, 1, 5]
.
We could sum these, but that wouldn't account for things like IV
. But if we negate any that are followed by a larger numeral, then we could sum them. We'll consider everything but the final digit.
for i in range(len(converted) - 1):
if converted[i] < converted[i + 1]:
converted[i] *= -1
Now converted
is [1000, -100, 1000, -10, 100, -1, 5]
.
And if we sum those numbers with sum(converted)
, we get 1994
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chris |