dante
dante

Reputation: 73

Stuck at converting integers into romans

I'm trying to convert integers into roman numerals using for loop. I started the code, but I'm currently stuck here, I don't know what to do(getting errors all the time). If anyone has any idea about how to continue this code, help would be much appreciated.

roman_digits = {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"}

empty = ""
rand_num = 153

for nums, alpha in roman_digits.items():
    if rand_num <= nums:
        empty += alpha
        rand_num -= nums

print(empty)

this code is not working

Upvotes: 0

Views: 103

Answers (2)

A. Pond
A. Pond

Reputation: 370

I adapted the code I found HERE to work outside of its class. The logic is all explained on the website.

rand_num = 153

val = [
    1000, 900, 500, 400,
    100, 90, 50, 40,
    10, 9, 5, 4,
    1
    ]
syb = [
    "M", "CM", "D", "CD",
    "C", "XC", "L", "XL",
    "X", "IX", "V", "IV",
    "I"
    ]
roman_num = ''
i = 0
while  rand_num > 0:
    for _ in range(rand_num // val[i]):
        roman_num += syb[i]
        rand_num -= val[i]
    i += 1
print(roman_num)

Upvotes: 2

Mark
Mark

Reputation: 92460

Your algorithm needs to alter the value of the input number at some point. For example, with input like 1053, on the first iteration you will discover M. At this point you are no longer interested in the 1000 place — you need the rest — 53. So you can add M to your output and continue on looking for 53. Then you find L and continue looking for 3. Something like this might get it going in a good direction:

def rn(rand_num):
    empty = ""

    while rand_num > 0:
        for nums, alpha in roman_digits.items():
            if rand_num >= nums:
                empty += alpha
                rand_num -= nums  # change rand_nums
                break

    return empty

Upvotes: 1

Related Questions