[英]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.