I am on a basic problem which outputs the number of coins types to be used to reach a sum which is inputted at method call.
Although I could do it in some other ways, I wanted to create a method and wanted to use multiple assignments.
The divide method is supposed to get 2 inputs, and should return division and remaining of the original value.
def divide(coin,value):
if value >= coin:
remains = value % coin
value = (value - remains) / coin
return value, remains
else:
return 0
The main function is below, it calls the divide function, sending coin and value as arguments, to have the number of coins and initial value to be updated.
def stamps(x):
fives, x = divide(5, x)
twos, x = divide(2, x)
print(fives, twos, x)
print stamps(0)
This works fine when the coin outputs are calculated as positive integers. (like an input of 8 will output (1,1,1)
) But If one or more coins are calculated as 0 (like, if you send 5, the output should be(1,0,0)
) but it gives the following error:
twos, x = divide(2, x) TypeError: 'int' object is not iterable
I did not use any iterations (not on purpose at least). Why am I having this error? If value is smaller than the coin, divide method should return 0 isn't that correct?
Your code is correct, the only problem is that you're returning only one value in else conditions, this is throwing this error.
Try the code below-
def divide(coin, value):
if value >= coin:
remains = value % coin
value = (value - remains) / coin
return value, remains
else:
return 0, 0 #or return 0, value
def stamps(x):
fives, x = divide(5, x)
twos, x = divide(2, x)
print(fives, twos, x)
print(stamps(0))