Basic program to convert integer to Roman numerals?

后端 未结 24 1361
孤独总比滥情好
孤独总比滥情好 2020-11-30 11:52

I\'m trying to write a code that converts a user-inputted integer into its Roman numeral equivalent. What I have so far is:

The point of the generate_

24条回答
  •  悲&欢浪女
    2020-11-30 12:29

    Here is another way, without division:

    num_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 num2roman(num):
    
        roman = ''
    
        while num > 0:
            for i, r in num_map:
                while num >= i:
                    roman += r
                    num -= i
    
        return roman
    
    # test 
    >>> num2roman(2242)
    'MMCCXLII'
    

    Update see the execution visualized

提交回复
热议问题