[英]Writing a function to convert a given integer into a roman numeral using Python programming
我正在做一些编码练习,并试图研究如何编写一个函数来将给定的整数转换为罗马数字。 下面是我写的代码:
roman_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC') , (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), ( 1, '我')]
def solution(n):
roman = '' #Set the variable roman to empty
while n>0: #While the entered integer is greater than 0
for key,value in roman_map: #loop through every key value in the roman numeral map
while n>=key: #while the entered integer is more than or equal to the key
roman+=value #Take the value of that key and add it to your empty roman numeral set
n-=key #Deduct the key from the entered integer
return roman
我尝试理解代码中使用的逻辑并理解以下内容:
我对最后一步失去了理解,这就是为什么必须从输入的整数中扣除密钥。 是否会在记录后从地图中删除该键值对? 有人可以帮我理解这个逻辑吗
您只需根据需要多次添加每个键。 您不会更改您的参考列表roman map
。 第 3 步是通用的,因此您可以处理诸如 1234 之类的重复字母。该内部while
循环将添加M
,然后是C
两次,然后是X
三次,最后是IV
。
如果您想更全面地理解代码,请执行尽职调查:插入几个战略性print
语句来跟踪数据和执行。 例如
print(key, value, n, roman)
应该给你一个很好的跟踪发生了什么。
最后一步是n-=key
,不,这不会从dict roman_map
删除任何dict roman_map
。 它所做的是从n
减去在刚刚完成的循环中找到罗马部分的数量。
整数日为 1001。代码将(简而言之)检查{1000: 'M'}
,将M
添加到roman
。 现在它必须从n
减去数量key (1000)
,留下1
,最终将在 for 循环中稍后处理,此时它将I
附加到字符串roman
。
总的来说,每次代码找到要添加的罗马数字时,它必须从整数中减去它所代表的数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.