简体   繁体   中英

Writing a function to convert a given integer into a roman numeral using Python programming

I'm doing some coding exercises and tried to research how to write a function to convert a given integer into a roman numeral. Below is the code I have written:

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, 'I')]

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

I tried understanding the logic used on the code and understood the following:

  1. Take an integer 1
  2. As long as 1 is greater than 0, loop through every key value pair in the roman numeral map
  3. As long as the integer is greater than or equal to the key, take the value of that key and add it to the empty variable 'roman'.

I'm lost understanding the last step which is why does the key have to be then deducted from the entered integer. Does that remove that key value pair from the map after it has been recorded? Can someone please help me understand this logic

You're simply adding each key as many times as needed. You do not alter your reference list roman map . Step 3 is generic, so that you can handle the repeated letters in something such as 1234. That inner while loop will add M , then C twice, then X three times and finally IV .

If you want to understand the code more fully, perform your due diligence: insert a couple of strategic print statements to trace the data and execution. For instance

print(key, value, n, roman)

should give you a good trace of what's going on.

The last step being n-=key , no this does not remove anything from the dict roman_map . What it does is to subtract from n , the amount for which a Roman part was found in the loop just completed.

Day the Integer is 1001. The code will (in short), will check for {1000: 'M'} , add M to roman . Now it must subtract the amount key (1000) from n , leaving 1 , which will eventually be processed later in the for loop, at which point it will append I to the string roman .

Overall, each time the code finds a roman numeral to add, it must subtract the amount it represents from the integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM