I am trying to understand the while
loop and sorted
call in the program to convert a number to Roman numerals below.
numerals = { 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" }
num = 58 # LVIII
roman = ''
for k, v in sorted(numerals.items(), reverse=True):
while num >= k:
roman += v
num -= k
print(roman)
Questions:
1) Why doesn't the code work if numerals.items()
is used instead of sorted(numerals.items(), reverse=True)
? (For example, 58 would result in IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
instead of LVIII
.) When using a breakpoint on that line it looks like the order remains same both with and without sorted
.
2) The first Roman numeral is L
. Why? When debugging I noticed it starts counting down from 1000. When it reaches 50, I see that roman == 'L'
. The code tests if num >= k
. 1000 (M) is also greater than 58. Why does the condition num >= k
result in L
being the first digit?
sorted(numerals.items(), reverse=True)
not only means sorted, but also means sorted in reverse. The key point is reverse=True
. Because we must compare to the largest Roman first. From M
to I
, not from I
to M
."The logic says num>=k. 1000,M is also greater than num 58."
I think you have misunderstanding here. for while num>=k:
it find less or equal than num, not large, so L
will be the first one. Hope that will help you.