Python Forum
Converting number to roman numerals
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting number to roman numerals
#1
Hi i have been trying to convert number to roman numerals all day but no luck, i know there is a readily available codes on internet with different algorithm, but i am trying a different approach(algorithm), which appears for me to mainly deal with differences.

my algorithm is below :

Example #1
x = 36
Answer:XXXVI

Iteration #	Decimal number (x)	Highest decimal value (v)	Highest roman numeral (n)	Temporary result
1	              36	                    10	                          X	                  X
2	              26	                    10	                          X	                  XX
3	              16	                    10	                          X                	  XXX
4	               6	                     5	                          V	                  XXXV
5	               1	                     1	                          I	                  XXXVI
Example #2
x = 2012
Answer: MMXII

Iteration #	Decimal number (x)	Highest decimal value (v)	Highest roman numeral (n)	Temporary result
1	               2012	                   1000	                         M	                   M
2	               1012	                   1000	                         M	                   MM
3	               12	                   10	                         X	                   MMX
4	               2	                   1	                         I	                   MMXI
5	               1	                   1	                         I	                   MMXII

Example #3
x = 1996
Answer: MCMXCVI
Iteration #	Decimal number (x)	Highest decimal value (v)	Highest roman numeral (n)	Temporary result
1	               1996	                       1000	                    M	                    M
2	               996	                       900	                    CM	                    MCM
3	               96	                       90	                    XC	                    MCMXC
4	               6	                       5	                    V	                    MCMXCV
5	               1	                       1	                    I	                    MCMXCVI
So far i have tried to implement this method like this in the below code:

class roman_num():
    
    def num_conv(number):
     h_num= [1,4,5,9,10,40,50,90,100,400,500,900,1000]
     Rom_num= ['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M']
     h_num_rev = h_num
     h_num_rev.reverse()
     Rom_num_rev = Rom_num
     Rom_num_rev.reverse()
        
     var_rom=[]
     var_num=[]
     num=number
    
     for ind,val in enumerate(h_num_rev):
            num-=val
            print('In for loop ',num,ind,val)
            
            while ((num>=0) and (num>val)):
                var_num.append(val)
                num-=val
                print('In while loop ',num,ind,val)
                if(num<0):
                    break
                 

            if(num<0):
                num=number
                
            if(num==1):
                var_num.append(1)
                
            
            
     return(var_num)
        
print(roman_num.num_conv(36))
it is just for practice, i have just started with python, i know i am no where near success, any help would be appreciated to implement.
Reply
#2
here are some packages you can look at: https://pypi.org/search/?q=roman
this may be useful: https://www.mathsisfun.com/roman-numerals.html
Reply
#3
Your Roman Numerals are in the wrong order. You provided a great example for how to solve the problem, then you wrote code that completely ignores the example.

In your example the first thing you did was find out how many 1000's there are in the number. For each 1000 you subtracted 1000 from the number and added 'M' to the Roman Numeral. Then you repeated this for the next lower value numeral (900 and CM). Repeat for every roman numeral in order of decreasing value until the remaining number is zero.

In your program you do the opposite. You start with the lowest value numeral work your way up. You know how to do this, don't freeze up just because you are now writing the algorithm in Python.

Maybe that is what you need, a written algorithm that can direct your coding.
def roman_numeral(number):
    # Map of roman numerals and values ordered in decreasing value.
    NUMERALS = {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'}
    # Start with an empty string
    retval = ''

    # Starting with the highest value, loop through all numerals
    ...:
        # While number is >= value, subtract value from number and add numeral to retval
        ...
    return retval
Next time write the comments yourself. If you have a hard time writing the comments it means you don't understand the problem. If you cannot write a good description of the algorithm you cannot write a program.
Reply
#4
From Wikipedia
https://en.wikipedia.org/wiki/Roman_numerals

Complete the code at (...) and you should be good to go.

:)

PS, of course it should be a class with converters, and the dictionary should be a class variable and etc. ...

def roman_numeral(n):

    dntor = {
        3000:'MMM',
        2000:'MM',
        1000:'M',
        900:'CM',
        800:'DCCC',
        700:'DCC',
        600:'DC',
        500:'D',
        400:'CD',
        300:'CCC',
        200:'CC',
        100:'C',
        90:'XC',
        80:'LXXX',
        70:'LXX',
        60:'LX',
        50:'L',
        40:'XL',
        30:'XXX',
        20:'XX',
        10:'X',
        9:'IX',
        8:'VIII',
        7:'VII',
        6:'VI',
        5:'V',
        4:'IV',
        3:'III',
        2:'II',
        1:'I',
        0:''
    }

    assert(0 < n < 4000)
    
    x = n%10
    rs = dntor[x]
    n -= x
    
    #...
    assert(n==0)

    return rs
Reply
#5
(Aug-09-2020, 04:31 AM)deanhystad Wrote: Your Roman Numerals are in the wrong order. You provided a great example for how to solve the problem, then you wrote code that completely ignores the example.

In your example the first thing you did was find out how many 1000's there are in the number. For each 1000 you subtracted 1000 from the number and added 'M' to the Roman Numeral. Then you repeated this for the next lower value numeral (900 and CM). Repeat for every roman numeral in order of decreasing value until the remaining number is zero.

In your program you do the opposite. You start with the lowest value numeral work your way up. You know how to do this, don't freeze up just because you are now writing the algorithm in Python.

Maybe that is what you need, a written algorithm that can direct your coding.
def roman_numeral(number):
    # Map of roman numerals and values ordered in decreasing value.
    NUMERALS = {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'}
    # Start with an empty string
    retval = ''

    # Starting with the highest value, loop through all numerals
    ...:
        # While number is >= value, subtract value from number and add numeral to retval
        ...
    return retval
Next time write the comments yourself. If you have a hard time writing the comments it means you don't understand the problem. If you cannot write a good description of the algorithm you cannot write a program.

Thanks a lot, it took me lot of time to figure it out, but was totally very useful tips, i will follow this in future.
Finally i was able to do it myself. Many thanks for giving me clarity, here is my code.

def roman_numeral(num):
    # Map of roman numerals and values ordered in decreasing value.
    NUMERALS = {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'}
    # Start with an empty string
    #retval = []
    retval=''
    #num = 1996
    
    # Starting with the highest value, loop through all numerals
    for i in NUMERALS:
        var=num-i
        print('In for loop ',i,' ',num,' ',var)
        # If number is >= value, subtract value from number and add numeral to retval
        if(var>=0):
            #retval.append(NUMERALS[i])
            retval=retval+NUMERALS[i]
            while (var>=i):
                #retval.append(NUMERALS[i])
                retval=retval+NUMERALS[i]
                var-=i
                print('In While loop ',i,' ',num,' ', var, ' ',retval )
            num=var
    return retval

roman_numeral(36)

(Aug-09-2020, 07:45 PM)voidptr Wrote: From Wikipedia
https://en.wikipedia.org/wiki/Roman_numerals

Complete the code at (...) and you should be good to go.

:)

PS, of course it should be a class with converters, and the dictionary should be a class variable and etc. ...

def roman_numeral(n):

    dntor = {
        3000:'MMM',
        2000:'MM',
        1000:'M',
        900:'CM',
        800:'DCCC',
        700:'DCC',
        600:'DC',
        500:'D',
        400:'CD',
        300:'CCC',
        200:'CC',
        100:'C',
        90:'XC',
        80:'LXXX',
        70:'LXX',
        60:'LX',
        50:'L',
        40:'XL',
        30:'XXX',
        20:'XX',
        10:'X',
        9:'IX',
        8:'VIII',
        7:'VII',
        6:'VI',
        5:'V',
        4:'IV',
        3:'III',
        2:'II',
        1:'I',
        0:''
    }

    assert(0 < n < 4000)
    
    x = n%10
    rs = dntor[x]
    n -= x
    
    #...
    assert(n==0)

    return rs
Thanks for helping hand, finally i solved it with the help of other comment suggestion.
Reply
#6
I would do this:
    retval = ''
    for numval, numstr in NUMERALS.items():  # returns key and value from dictionary
        while num >= numval:
            num -= numval
            retval += numstr
    return retval
Python can be amazing in its brevity.
Reply
#7
this is it for me :)

def roman_numeral(n):

    dntor = {
        3000:'MMM', 2000:'MM', 1000:'M',
        900:'CM', 800:'DCCC', 700:'DCC', 600:'DC', 
        500:'D', 400:'CD', 300:'CCC', 200:'CC', 100:'C', 
        90:'XC', 80:'LXXX', 70:'LXX', 60:'LX', 50:'L', 40:'XL', 30:'XXX', 20:'XX', 10:'X',
        9:'IX', 8:'VIII', 7:'VII', 6:'VI', 5:'V', 4:'IV', 3:'III', 2:'II', 1:'I',
        0:''
    }

    assert(0 < n < 4000)

    x = n%10
    rs = dntor[x]
    n -= x
    x = n%100
    rs = dntor[x] + rs
    n -= x
    x = n%1000
    rs = dntor[x] + rs
    n -= x
    x = n%10000
    rs = dntor[x] + rs

    n -= x
    assert(n==0)

    return rs

#-------


s = roman_numeral(100)
s = roman_numeral(3999)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with implementation of the logic to convert roman numeral to integer jagasrik 2 2,307 Aug-14-2020, 07:31 PM
Last Post: deanhystad
  Roman Numeral Ordered List? (first post) CopperyMarrow15 1 1,723 Nov-06-2019, 11:06 PM
Last Post: Larz60+
Question [Help] Convert integer to Roman numerals? {Screenshot attached} vanicci 10 9,179 Aug-06-2018, 05:19 PM
Last Post: vanicci

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020