gpt4 book ai didi

python - 在python中将罗马数字转换为整数

转载 作者:太空狗 更新时间:2023-10-29 17:36:43 24 4
gpt4 key购买 nike

根据 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()

我在 while ns 中遇到了这个错误:UnboundLocalError: 赋值前引用了局部变量 'ns'

最佳答案

无需重新发明轮子(除非您愿意)。 Python 曾经附带一个转换器(因此您可以转到 Python 3.4.1 source code 并在以下位置获取模块:/Python-3.4.1/Doc/tools/roman.py;或者安装它正如评论中有人所说的那样使用 pip;我还没有验证 pip 版本;无论如何,你可以这样做):

import roman;
n=roman.fromRoman("X"); #n becomes 10

如果您需要它来表示 5000 及以上的数字,您将需要编写一个新函数,并且可能制作您自己的字体来表示罗马数字上的线条。 (它只适用于某些数字。停在 4999 是一个非常好的主意。)

要转换为罗马数字,请使用 roman.toRoman(myInt)

或者(仅用于转换为罗马数字),您可以在 Python 3.9.2 中执行此操作(由于缺乏文档,我只能部分理解;因此,我的所有论点可能都不正确;但是,看起来工作;无论如何格式化程序都会贬值;所以,不要指望它会长期存在):

import formatter
a=formatter.AbstractFormatter("I don't know what I'm supposed to put here, but it doesn't seem to matter for our purposes.")
roman_numeral=a.format_roman(case="I", counter=5) #Case doesn't seem to matter, either.
#roman_numeral now equals "V"

其他人实际上链接到 roman 模块在上面的评论之一中使用的相同源代码,但我不相信他们提到它实际上与 Python 一起提供。它似乎不再与 Python 一起提供,但它在 3.4.1 版本中提供。

关于python - 在python中将罗马数字转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19308177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com