0
Plz explain me this code?
def solution(n): roman_numerals = {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' } roman_string = '' for key in sorted(roman_numerals.keys(),reverse=True): while n >= key: roman_string += roman_numerals[key] n -= key return roman_string
6 odpowiedzi
+ 4
the header of the for loop does not need sorting as done here, since the dict roman_numerals is already in the required order:
#for key in sorted(roman_numerals.keys(),reverse=True):
for key in roman_numerals.keys(): # this is ok !
+ 2
as already mentioned in my first post, there is no need to use sorting or reversing the dictionary that is defined in the code.
please feel free to test it. to understand what the code is doing, it is recommended to use a debugger and step through the program.
here is a working version of the code without sorting and or reversing the dict:
https://code.sololearn.com/cvHrDJGttc7c/?ref=app
+ 1
#You can save this code in SL Playground and put in a few places a print statements:
#maybe not all togther
#so you can see what happend
def solution(n):
roman_numerals = {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'
}
roman_string = ''
print(sorted(roman_numerals.keys(),reverse=True))
for key in sorted(roman_numerals.keys(),reverse=True):
print(key)
while n >= key:
print(key)
print(roman_string)
roman_string += roman_numerals[key]
print(roman_string)
n -= key
print(n)
return roman_string
solution(int(input()))
0
Which part you don’t understand?
0
Using the for loop
0
It’s already sorted. But in this case sorted function is used to reverse these keys.
So, you need to use a reverse function