麻烦在Python中将罗马数字转换为整数

时间:2015-05-07 19:32:44

标签: python roman-numerals

不太确定我做错了什么。使用Python 3.2获取问题:     TypeError:list indices必须是整数,而不是list

这是我的代码。

print('Please input your first Roman Numeral.')
ri1 = input()

def romantointeger(x):
conversion = [['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10]]     #creates Roman numer values
retint = 0 #creates the variable that will eventually be returned as the final value
for pair in conversion:
        cont = True #makes it continue for a pair
        while cont:
            if len(x) >= len(pair): #checks the length to see if it is greater than a pair of [0]
                if x[0:len(pair)]: 
                    retint += conversion[pair]
                    string = string[len(pair):]
                else:
                    cont = False
            else:
                cont = False
return retint

romantointeger(ri1)

3 个答案:

答案 0 :(得分:1)

conversion ={'M':1000,'CM':900,'D':500,'CD':400,'C':100,'XC':90,'L':50,'XL':40,'X':10,}     
for pair in conversion:

对将迭代字典的密钥。

尝试

for pair in conversion.items():

甚至更好:

for key, value in conversion.items():

答案 1 :(得分:0)

conversion是一本字典。这意味着循环遍历它for pair in conversion,因为这将指定字典的每个键配对。

这意味着: retint += pair[1]应为retint += conversion[pair]

任何时候pair[0] pair都应该for key in conversion: print key

然而,由于字典未排序(您的订单不一定与您输入的内容相同),这仍然无法正常工作(您可能)。这意味着您的代码将无法正常工作你期望(因为输入将是一个字符串"排序"这样最大的值首先出现。)

示范:

conversion

给了我:

  

X
  ç
  XC
  CD
  d
  XL
  CM
  大号
  M

绝对不是你想要的!

您想要的是将conversion = ['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10]]定义为列表列表,以便每个元素都是罗马数字及其值。 所以:

pair[0]

您可以单独保留其余代码,并且它可以按照您的要求工作,因为现在pair[1]将被定义为罗马数字代码,In [1]: mydict = {"aaron":["1","4","10\n","3","6"] , "paul":["7","4\n","6","15"]} In [2]: for k,L in mydict.items(): ...: for i,elem in enumerate(L): ...: L[i] = elem.strip() ...: In [3]: mydict Out[3]: {'aaron': ['1', '4', '10', '3', '6'], 'paul': ['7', '4', '6', '15']} 将是其数值(修复)你的TypeError!)。此列表也将按照确切的顺序排列。

答案 2 :(得分:0)

class Solution(object):
def romanToInt(self, s):
    """
    :type s: str
    :rtype: int
    """
    single = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    num  = 0
    flag = -1

    if s in single:
        num += single[s]
        return num
    elif s not in single:
        for i in range(len(s)):
            if i == flag:
                pass
            elif i != flag:
                if i <= len(s)-2:
                    if single[s[i]] < single[s[i+1]]:
                        num += single[s[i+1]]-single[s[i]]
                        flag = i+1
                    else:
                        num += single[s[i]]
                else:
                    num += single[s[i]]
        return num