My assignment is:
where the input target_amount is a single non-negative integer value and the input L is a list of positive integer values. Then, exact_change should return either True or False: it should return True if it's possible to create target_amount by adding up some-or-all of the values in L. It should return False if it's not possible to create target_amount by adding up some-or-all of the values in L.
For example, L could represent the coins you have in your pocket and target_amount could represent the price of an item – in this case, exact_change would tell you whether or not you can pay for the item exactly.
Here are a few examples of exact_change in action. Notice that you can always make change for the target value of 0, and you can never make change for a negative target value: these are two, but not all, of the base cases!
The function I wrote is:
def exact_change( target_amount, L ):
if target_amount > sum(L):
return False
elif target_amount == 0:
return True
elif target_amount < 0:
return False
elif target_amount > 0 and L==[]:
return False
elif target_amount == L:
return True
else:
loseit = exact_change(target_amount, L[1:])
useit = exact_change(target_amount, L[0])
return loseit or useit'
And the outcame has to be:
>>> exact_change( 42, [25, 1, 25, 10, 5, 1] )
True
>>> exact_change( 42, [25, 1, 25, 10, 5] )
False
>>> exact_change( 42, [23, 1, 23, 100] )
False
>>> exact_change( 42, [23, 17, 2, 100] )
True
>>> exact_change( 42, [25, 16, 2, 15] )
True # needs to be able to "skip" the 16...
>>> exact_change( 0, [4, 5, 6] )
True
>>> exact_change( -47, [4, 5, 6] )
False
>>> exact_change( 0, [] )
True
>>> exact_change( 42, [] )
False
But my outcome is:
TypeError: 'int' object is not iterable
Please help me! What am I missing?
For the useit recursive call, you are passing a single int instead of the remaining list, see below:
def exact_change( target_amount, L ):
if target_amount > sum(L):
return False
elif target_amount == 0:
return True
elif target_amount < 0:
return False
elif target_amount > 0 and not L:
return False
else:
loseit = exact_change(target_amount, L[1:])
# reduce target amount since we use current coin
useit = exact_change(target_amount - L[0], L[1:])
return loseit or useit
You are trying to iterate through a single integer. This is not possible. You iterate through a list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.