0

I don't understand this code plz explain me

num_map = [(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')] def num2roman(num): roman = '' while num > 0: for i, r in num_map: while num >= i: roman += r num -= i return roman # test print(num2roman(3000009))

11th Aug 2021, 3:21 PM
Shahir
Shahir - avatar
7 odpowiedzi
+ 2
What's the expected output?
11th Aug 2021, 3:24 PM
Chloe
Chloe - avatar
+ 2
I'm not really sure how to go about doing that, but I'm pretty sure that place value plays a large role, and perhaps you could split the number into different chunks..? I'm sorry not of much help-
11th Aug 2021, 3:35 PM
Chloe
Chloe - avatar
+ 2
No problem you tried to help me I really appreciate it
11th Aug 2021, 3:37 PM
Shahir
Shahir - avatar
+ 2
Shahir Let's understand just for small number like 3000 So there are 3 loop while, for and while Also you have an array containing tuples. So let's for 3000 while num > 0 will be True so for loop will execute where we are taking key and value of each tuples from the aray. Now we have i = 1000 and r = 'M' So 3000 >= 1000 is True so while loop will execute and roman = roman + r = M But now num = num - i = 3000 - 1000 = 2000 So now while 2000 >= 1000 which is True and in this case roman = roman + r = 'M' + 'M' = MM Remember previous roman was M so new Roman is MM Now again num = num - i = 2000 - 1000 = 1000 Now again while 1000 >= 1000 is True so again roman will be MMM But now num will be 0 because of 1000 - 1000 = 0 so now inner while loop will not execute because finally 'num' is 0 and outer loop will also be not execute because num > 0 is False So finally result is MMM
11th Aug 2021, 3:40 PM
A͢J
A͢J - avatar
+ 2
Thanks nice explanation
11th Aug 2021, 11:45 PM
Shahir
Shahir - avatar
+ 1
Task is to convert a integer into a Roman number
11th Aug 2021, 3:32 PM
Shahir
Shahir - avatar
0
↗️↗️↗️↗️
12th Aug 2021, 4:08 PM
Zerabi manar eddine
Zerabi manar eddine - avatar