简体   繁体   English

这是 integer 程序的罗马数字,但 output 不是我所期望的

[英]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 .我希望1994为 output,但是当输入为MCMXCIV时我得到1014 Can you please give suggestions where my code went wrong.您能否就我的代码出错的地方提出建议。 im a beginner to python, Thank you.我是 python 的初学者,谢谢。

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')

There is a simpler approach.有一种更简单的方法。 Let's map each numeral to its value.让我们将 map 每个数字改为它的值。

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] .现在converted[1000, 100, 1000, 10, 100, 1, 5]

We could sum these, but that wouldn't account for things like IV .我们可以总结这些,但这不能解释像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] .现在converted[1000, -100, 1000, -10, 100, -1, 5]

And if we sum those numbers with sum(converted) , we get 1994 .如果我们将这些数字与sum(converted) ,我们得到1994

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:例如,IX(即 9)不是 V(即 5),XC(即 90)不是 V (5),等等。替换:

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.然后代码按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM