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

23rd Aug 2021, 3:28 PM
Shahir
Shahir - avatar
6 Answers
+ 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 !
23rd Aug 2021, 3:47 PM
Lothar
Lothar - avatar
+ 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
24th Aug 2021, 5:52 PM
Lothar
Lothar - avatar
+ 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()))
23rd Aug 2021, 4:01 PM
JaScript
JaScript - avatar
0
Which part you don’t understand?
23rd Aug 2021, 3:39 PM
Iftekhar Ahmed Pranto
Iftekhar Ahmed Pranto - avatar
0
Using the for loop
23rd Aug 2021, 3:44 PM
Shahir
Shahir - avatar
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
23rd Aug 2021, 3:56 PM
Iftekhar Ahmed Pranto
Iftekhar Ahmed Pranto - avatar