Convert from numbers to roman notation

jopp picture jopp · Nov 2, 2015 · Viewed 7.4k times · Source

I want to convert from numbers to roman notations. I have been given a list which looks like this:

conv = [[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']]

where input should be an integer between 0 and 3999. So I want to construct a function which takes an argument (integer) and convert it. I have a little problem solving this. Any help would be appreciated. Here is how I think:

First I want some input of an integer which I store in a variable, so I will use something like

number = input("Enter a number between 0 and 3999: ")

conv = [[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']]

For the last step I want to use 2 loops to solve the actual problem. Which looks something like this:

for char in number:
    i = 0;
    while i < len(conv):
        if int(char) == int(conv[i][0]):
            print(conv[i][1])
            i += 1;
        else:
            i += 1;

I know this code is wrong, but perhaps not the idea. First I want to loop through every 'char' (character) in the string number. For this purpose I will also define a variable 'i' which I set to 0. This variable 'i' will be used in a while loop which should be executed as long as i is less than the length of the list conv. Then I want to compare if the integer char is equal to the integer part of conv at index [i][0] (0 because I always want to compare to the number parts in the list and i because I want to loop through every possiblity. If they match then I want to do something, I don't really know what I want to do at this step, but I would like to print out something. At this step I would like to tell the program to construct the roman notation, and also increment i. Else just increment i. I have to make the program understand that 12 is represented as XII and so on. Any ideas how I could solve this problem. Thanks :)

Answer

Robᵩ picture Robᵩ · Nov 2, 2015

Here's how I'd do it. This program loops through the conv array, at each step appending the appropriate roman numerals to result.

def arabic_to_roman(number):
    conv = [[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']]
    result = ''
    for denom, roman_digit in conv:
        result += roman_digit*(number/denom)
        number %= denom
    return result

for i in 1,4,9,16,25,49,81,1963,2015:
    print i, arabic_to_roman(i)