-4

I saw this unfinished code on the internet:

class py_solution:  
def int_to_Roman(self, num):  
    val = [  
        1000, 900, 500, 400,  
       ?????,
       ????,
        ?
        ]  
    syb = [  
        "M", "CM", "D", "CD",  
        "C", "XC", "L", "XL",  
        "X", "IX", "V", "IV",  
        "I"  
        ]  
    roman_num = ?
    i = ? 
    while  ???:  
        for _ in range(???):  
            roman_num += ???
            num -= ???
        i += ???  
    return ???

And I got curious about how to solve it. (I am new to Python, and this is not my homework)

1 Answers1

3
def int_to_Roman(num):
   val = (1000, 900,  500, 400, 100,  90, 50,  40, 10,  9,   5,  4,   1)
   syb = ('M',  'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
   roman_num = ""
   for i in range(len(val)):
      count = int(num / val[i])
      roman_num += syb[i] * count
      num -= val[i] * count
   return roman_num

so you create val and syb which you'll use for mapping int values to roman values. after that you take int values one by one and check how many of those will fit in your input value, and you add that amount of roman nums to result, and you remove the added value from input and repeat the process until you reach zero.

gmed
  • 140
  • 1
  • 10
  • Is there a way to do it with modules like in my question? – John Finkelstein Mar 18 '17 at 13:55
  • Like to change the question marks? – John Finkelstein Mar 18 '17 at 13:55
  • as you can see the code is pretty much identical. your val is ints, your syb is nums. your roman_num is result and your num is input. i'll fix the code – gmed Mar 18 '17 at 13:57
  • Thank You, what do you mean by fix? – John Finkelstein Mar 18 '17 at 14:00
  • Yes Thank You, but when I try to run the code it does nothing. And I did `int_to_Roman(num)` – John Finkelstein Mar 18 '17 at 14:02
  • try with this to check if its working. ( I've tried and it works) print(int_to_Roman(200)) should print CC also, please mark my answer as correct if it helped you. Thanks – gmed Mar 18 '17 at 14:03
  • Oh Ok! And can you explain how does the code work? – John Finkelstein Mar 18 '17 at 14:05
  • you have a short explanation in the description. you create val and syb which you'll use for mapping int values to roman values. after that you loop through values and check how many times can each fit in your number. after that you add roman numbers to answer and you reduce inputed number by the inserted value. for example : you want 500 in roman it will take 500, and try with 1000, 500/ 1000 is 0 so nothing happens, then it takes 900 and tries 500/900, nothing happens.but then 500/500 is 1. and it adds D to roman_num and reduces input by 500 so its 0. – gmed Mar 18 '17 at 14:10
  • Hello again Goran, I got curious again, is there a way to do it backwards? Like if my input is II my output will be 2? – John Finkelstein Mar 18 '17 at 14:28