Python将罗马数字转换为整数

2024-10-06 12:13:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试了以下从罗马到整数的python3代码

代码一目了然运行良好。但是,当我输入XV或与XV值相关时,出现了某些问题

例如:当我尝试V时,代码不起作用,但IV显示正确的值

我的代码:

class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
if message <= ("MMMCMXCIX"):
   print (ob1.romanToInt(message))
else:
    print ("Try again")

我设置了一个条件,如果输入的罗马数字等于或小于MMMCMXCIX,它将打印罗马数字;否则它将打印Try again

问题是当我输入XV或与XV相关的值时,输出显示Try again

请帮助我理解我哪里出了错


Tags: 代码messagelenifelsenumprintsolution
3条回答

正如注释中提到的,问题是因为比较了字符串而不是首先转换为int,然后进行比较

您可以尝试的其他方法是:

def romanToInt(s):
  d = {'m': 1000, 'd': 500, 'c': 100, 'l': 50, 'x': 10, 'v': 5, 'i': 1}
  n = [d[i] for i in s.lower() if i in d]
  return sum([i if i>=n[min(j+1, len(n)-1)] else -i for j,i in enumerate(n)])

print(romanToInt('X')) # 10
print(romanToInt('V')) # 5
print(romanToInt('IV')) # 4
print(romanToInt('XV')) # 15

在我看来,两者都更像Python

最后,它只是一个数字的加法,你只需要弄清楚它们是否需要被解释为正数或负数:

roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}

def roman2Dec(inp):
    inpNum = [roman[x] for x in inp]
    return sum([-x if i < len(inpNum)-1 and x < inpNum[i+1] else x for i, x in enumerate(inpNum)])

for nums in [('IX', 9), ('XL', 40), ('LXI', 61), ('MMMCMXCIX', 3999)]:
    result = roman2Dec(nums[0])
    print result == nums[1]

输出:

True
True
True
True

这是因为您要比较字符串,而不是首先将罗马字符转换为int而不是check

class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
# converting to integer than comparing the value of "MMMCMXCIX"
if ob1.romanToInt(message) <= 8999:
   print (ob1.romanToInt(message))
else:
    print ("Try again")

相关问题 更多 >