mardi 18 février 2020

Convert a roman numeral to an integer. Python3 [closed]

I need to understand if statement, how it works, if and else, other things in this program are easy to me.

def roman_to_int(roman):
    rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    int_val = 0
    for item in range(len(roman)):
        if item > 0 and rom_val[roman[item]] > rom_val[roman[item - 1]]:
            int_val += rom_val[roman[item]] - 2 * rom_val[roman[item - 1]]
        else:
            int_val += rom_val[roman[item]]
    return int_val

print(roman_to_int('XXI'))

Aucun commentaire:

Enregistrer un commentaire