简体   繁体   English

整数到罗马数字,不能使用 def。 功能

[英]integer to roman numeral, cannot use def. function

I have a homewrok assignment to convert a roman numeral to an integer.我有一个家庭作业将罗马数字转换为整数。 I am stuck at the part of the actual "formula" to change the roman numerals to integers and subtract/add them to the next one.我被困在实际“公式”的一部分,将罗马数字更改为整数并将它们减去/添加到下一个。 We have not learned the "def" function yet so I cannot use that.我们还没有学习“def”函数,所以我不能使用它。 Here is the code I have so far.这是我到目前为止的代码。 I am just three weeks into coding so it is probably not very good..我只有三个星期的编码,所以它可能不是很好..

DictOfRomanNumerals = {"I":1, "II":2, "III":3, "IV":4, "V":5, "IX":9, "X":10,
                       "XL":40, "L":50, "XC":90, "C":100, "CD":400, "D":500,
                       "CM":900, "M":1000}

UserInput = input("Type in a Roman Numeral")

i=0
ouput=0

for i in range(0, len(UserInput)):
    i = i + 1

    if len(UserInput) == 1:
        print((DictOfRomanNumerals[UserInput[0]]))
    else:
        if len(UserInput) > 1: 

To solve this, create some possible numerals and their values and some special values like 4, 9, 40, 90, 400, 900. Now scan the given string, if some substring is present in the table, then take its value into result, then check for the next, for next match, it adds the value with the result, finally forms the number.为了解决这个问题,创建一些可能的数字及其值和一些特殊值,如 4、9、40、90、400、900。现在扫描给定的字符串,如果表中存在某个子字符串,则将其值放入结果中,然后检查下一个,对于下一个匹配,它将值与结果相加,最后形成数字。

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}
          s = input("Type in a Roman Numeral")
          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
          print(num)

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

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