我在互联网上看到了这个未完成的代码:
class py_solution:
def int_to_Roman(self, num):
val = [
1000, 900, 500, 400,
?????,
????,
?
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ?
i = ?
while ???:
for _ in range(???):
roman_num += ???
num -= ???
i += ???
return ???
我很好奇如何解决它。 (我是Python新手,这不是我的作业)
答案 0 :(得分:2)
def int_to_Roman(num):
val = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
syb = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
roman_num = ""
for i in range(len(val)):
count = int(num / val[i])
roman_num += syb[i] * count
num -= val[i] * count
return roman_num
所以你创建了val和syb,你将它用于将int值映射到罗马值。 之后,逐个获取int值并检查其中有多少个值适合您的输入值,然后将该量的罗马数字添加到结果中,并从输入中删除添加的值并重复该过程直到达到零。