Reputation: 75
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')
Upvotes: 0
Views: 99
Reputation: 36611
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
.
Upvotes: 3
Reputation:
You replace some of the Roman numerals wrong. For example, IX (which is 9) is not V (which is 5), XC (which is 90) is not V (5), etc. Replace:
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')
with
s = s.replace('IV', 'IIII').replace('IX', 'VIIII') #using replace function for exceptions
s = s.replace('XL', 'XXXX').replace('XC', 'LXXXX')
s = s.replace('CD', 'CCCC').replace('CM', 'DCCCC')
then the code works as expected.
Upvotes: 1