user15988667
user15988667

Reputation:

Decimal to Roman conversion program giving wrong answer in Python

I am writing a program to convert Decimal number to roman, but it is not printing correct answer for some numbers.

Here is my python code.

num = 600

d = {
    1: "I",
    4: "IV",
    5: "V",
    9: "IX",
    10: "X",
    40: "XL",
    50: "L",
    90: "XC",
    100: "C",
    400: "CD",
    500: "D",
    900: "CM",
    1000: "M",
}

t = 0
ans = ""
while num>0:
    for key in d.keys():
        if key < num:
            t = key
    num -= t
    ans = ans + d[t]

print(ans)

It prints DXCIXIX but the answer should be DC

Upvotes: 0

Views: 69

Answers (2)

Amal K
Amal K

Reputation: 4919

Alternate solution:

roman = ""
for key in sorted(d.keys(), reverse=True):
    while num >= key:
        roman += d[key]
        num -= key
print(roman)

Upvotes: 0

heijp06
heijp06

Reputation: 11808

Replace key < num with key <= num:

while num>0:
    for key in d.keys():
        if key <= num:
            t = key
    num -= t
    ans = ans + d[t]

Upvotes: 2

Related Questions