tby - 29 days ago 4x

Python Question

I understand there were many similar questions being asked on this topic. But I still have some doubts need to be clear.

`def int_to_roman(input):`

if type(input) != type(1):

raise TypeError, "expected integer, got %s" % type(input)

if not 0 < input < 4000:

raise ValueError, "Argument must be between 1 and 3999"

ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)

nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')

result = ""

for i in range(len(ints)):

count = int(input / ints[i])

result += nums[i] * count

input -= ints[i] * count

return result

I dont really understand the code below:

`for i in range(len(ints)):`

count = int(input / ints[i])

result += nums[i] * count

input -= ints[i] * count

Does:

`for i in range (len(ints)):`

it means '1000','900','800' (the integers respectively) or it means 13 (13 integers in integers)?

`count = int(input / ints[i])`

what does ints [i] mean?

Anyone please explain these codes? It would be best if you could show the examples (like substitute numbers and show how it works)

Answer

The two lists, `ints`

and `nums`

are the same length. The loop iterates over the length of `ints`

, which means that the variable `i`

can access the same position of either list, matching one to the other.

If we step through the loop, `count`

is assigned the integer value of the input divided by the first number in `ints`

, which is 1000. If the `input`

variable is, say, 10, then 10/1000 will result in a number <1, and using `int()`

on the result will cause it to assign 0 to `count`

. When 0 is multiplied by the matching string from `nums`

, the assigned result is basically nothing. Then the same amount is subtracted from `input`

, which in this case leaves it unchanged.

Eventually, the loop will reach a point when the result of the division is a number >=1, so the following steps will do something.

Let's say the result of `int(input / ints[i])`

is 3. `"X" * 3`

results in `"XXX"`

, which is added to `result`

, and the `input`

is reduced by the appropriate amount, in this case 30. So on, until the loop ends.

Source (Stackoverflow)

Comments