罗马整数到integeres - 简单

时间:2015-10-17 01:08:06

标签: python python-3.x for-loop roman-numerals

赋值要求将罗马整数转换为整数。 BUt没有与罗马整数相关的语法(即IV!= 4 IV = 6)我试图让我的代码更有效...

这是我的原始代码:

def roman_v2():
    s = input("Enter a roman number using capital letters M, D, C, X, V and I: ")
    count = 0
    r_nums = ["M","D","C","X","V","I"]
    for letter in s:
        if letter in r_nums[0]:
            count += 1000
        elif letter in r_nums[1]:
            count += 500
        elif letter in r_nums[2]:
            count += 100
        elif letter in r_nums[3]:
            count += 10
        elif letter in r_nums[4]:
            count += 5
        elif letter in r_nums[5]:
            count += 1    
    return count

这是我的错误程序:

def roman_v2():
    s = input("Enter a roman number using capital letters M, D, C, X, V and I: ")
    count = 0
    r_nums = [["M",1000],["D",500],["C",100],["X",10],["V",5],["I",1]]
    for i in s:
        for j in range(0,5):
            if s[i] == r_nums[j][0]:
                count += r_nums[i][1]
    return count

3 个答案:

答案 0 :(得分:1)

您可以使用字典和sum()功能

来收紧代码
def roman_v2():
    s = input("Enter a roman number using capital letters M, D, C, X, V and I: ")
    numbers = {'M':1000, 'D':500, 'C':100, 'X':10, 'V':5, 'I':1}
    return sum(numbers[num] for num in s)

这将查找每个字母的值,将它们全部添加,并返回总计。错误检查(对于错误的输入,如'MMpotato')取决于您。

答案 1 :(得分:1)

if s[i] == r_nums[j][0]:

应该是

if i == r_nums[j][0]:

因为我将成为角色,而不是指数。

count += r_nums[i][1]中,我错了,应该是j。

给你

def roman_v2():
    s = input("Enter a roman number using capital letters M, D, C, X, V and I: ")
    count = 0
    r_nums = [["M",1000],["D",500],["C",100],["X",10],["V",5],["I",1]]
    for i in s:
        for j in range(0,5):
            if i == r_nums[j][0]:
                count += r_nums[j][1]
    return count

答案 2 :(得分:0)

您可以在python中使用dict

def roman_v2():
    s = s = input("Enter a roman number using capital letters M, D, C, X, V and I: ")
    r_nums = {'M': 1000, 'D': 500, 'C': 100, 'X': 10, 'V': 5, 'I': 1}
    count = 0
    for i in s:
        count += r_nums.get(i)
    return count