这是继user2486之后我现在的代码。
def romanMap():
map=(("M", 1000),("CM", 900),("D", 500),("CD", 400),("C", 100),("XC", 90),("L", 50),("XL", 40),("X", 10),("IX", 9),("V", 5),("V", 4),("I", 1))
return map
firstNum=ns([0])
secondNum=ns([1])
def main():
ns=str(input("Enter a roman numeral"))
total=0
result=0
while ns:
firstNum=(romanMap(ns[0]))
secondNum=(romanMap(ns[1])
if firstNum is len(ns)>1 or secondNum-1:
total=total+firstNum
ns=ns[1:]
else:
total=total+ns[1]-ns[0]
ns=ns[2:]
print (total)
main()
当ns: unbundlocalerror:赋值前引用的局部变量'ns'
不需要重新发明轮子(除非你愿意)。Python附带一个转换器:
如果您需要它的数字5000及以上,您将需要编写一个新的函数,不过,也许您自己的字体来表示线超过罗马数字。(这只会对一些数字起作用。停在4999是个好主意。)
要转换为罗马数字,请使用
roman.toRoman(myInt)
。其他人实际上链接到了roman模块在上面的一条注释中使用的相同源代码,但我不相信他们提到它实际上是随Python一起提供的。
编辑:请注意,在某些系统(我认为是Windows)上,您不能只从默认安装中键入
import roman
。但是,源代码仍然可以在Windows上运行,它包含在Python 3.4.1源代码下载中(可能也是早期的版本),下载位置是/Python-3.4.1/Doc/tools/roman.py
罗马数字是从左到右读取的,当您添加或减去每个符号的值时。
如果一个值低于下面的值,它将被减去。否则将被添加。
例如,我们要将罗马数字MCMLIV转换为阿拉伯数字:
我们现在可以计算出这个数字:
参考号:http://www.mathinary.com/roman_numerals_from_roman_numerals_to_arabic_numbers.jsp
考虑一下这个额外的伪代码和提示(有些是有效的Python,有些不是,但是有注释)。
相关问题 更多 >
编程相关推荐