Basic program to convert integer to Roman numerals?

后端 未结 24 1362
孤独总比滥情好
孤独总比滥情好 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:11

    The approach by Laughing Man works. Using an ordered dictionary is clever. But his code re-creates the ordered dictionary every time the function is called, and within the function, in every recursive call, the function steps through the whole ordered dictionary from the top. Also, divmod returns both the quotient and the remainder, but the remainder is not used. A more direct approach is as follows.

    def _getRomanDictOrdered():
        #
        from collections import OrderedDict
        #
        dIntRoman = OrderedDict()
        #
        dIntRoman[1000] = "M"
        dIntRoman[900] = "CM"
        dIntRoman[500] = "D"
        dIntRoman[400] = "CD"
        dIntRoman[100] = "C"
        dIntRoman[90] = "XC"
        dIntRoman[50] = "L"
        dIntRoman[40] = "XL"
        dIntRoman[10] = "X"
        dIntRoman[9] = "IX"
        dIntRoman[5] = "V"
        dIntRoman[4] = "IV"
        dIntRoman[1] = "I"
        #
        return dIntRoman
    
    _dIntRomanOrder = _getRomanDictOrdered() # called once on import
    
    def getRomanNumeralOffInt( iNum ):
        #
        lRomanNumerals = []
        #
        for iKey in _dIntRomanOrder:
            #
            if iKey > iNum: continue
            #
            iQuotient = iNum // iKey
            #
            if not iQuotient: continue
            #
            lRomanNumerals.append( _dIntRomanOrder[ iKey ] * iQuotient )
            #
            iNum -= ( iKey * iQuotient )
            #
            if not iNum: break
            #
        #
        return ''.join( lRomanNumerals )
    

    Checking the results:

    >>> getRomanNumeralOffInt(35)
    'XXXV'
    >>> getRomanNumeralOffInt(994)
    'CMXCIV'
    >>> getRomanNumeralOffInt(1995)
    'MCMXCV'
    >>> getRomanNumeralOffInt(2015)
    'MMXV'
    

提交回复
热议问题