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
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