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))
7 odpowiedzi
+ 2
What's the expected output?
+ 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-
+ 2
No problem you tried to help me I really appreciate it
+ 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
+ 2
Thanks nice explanation
+ 1
Task is to convert a integer into a Roman number
0
↗️↗️↗️↗️