Help with small program
Paul Watson
pwatson at redlinepy.com
Mon Dec 25 00:05:00 EST 2006
smartbei wrote:
> Felix Benner wrote:
>> smartbei schrieb:
>>> Hello, I am a newbie with python, though I am having a lot of fun using
>>> it. Here is one of the excersizes I am trying to complete:
>>> the program is supposed to find the coin combination so that with 10
>>> coins you can reach a certain amoung, taken as a parameter. Here is the
>>> current program:
>>>
>>> coins = (100,10,5,1,0.5)
>>> anslist = []
>>> def bar(fin, hist = {100:0,10:0,5:0,1:0,0.5:0}):
>>> s = sum(x*hist[x] for x in hist)
>>> l = sum(hist.values())
>>> if s < fin and l < 10:
>>> for c in coins:
>>> if (s+c) <= fin:
>>> hist[c] += 1
>>> bar(fin, hist)
>>> hist[c] -= 1
>>> elif l==10 and s==fin and not hist in anslist:
>>> #p1
>>> anslist.append(hist)
>>>
>>> bar(50)
>>> print anslist
>>>
>>> The problem is that if I run it, anslist prints as [{0.5: 0, 1: 0, 10:
>>> 0, 100: 0, 5: 0}], which doesnt even add up to 50. When I check how
>>> many times the program has reached the #p1 by sticking a print there,
>>> it only reaches it once, and it comes out correct. why is it that this
>>> result is replaced by the incorrect final one?
>>>
>> hist is stored in anslist as a pointer only, therfore the hist[c] -= 1
>> operates on the same dict as is stored in the anslist. Try the following
>> in the python interpreter:
>>
>> a = { 'key' : 1 }
>> l = [a]
>> l[0]['key'] -= 1
>> a
>>
>> instead use:
>>
>> anslist.append(dict(hist.items))
>>
>> which will copy the dict.
>
> Thanks!
> BTW - its hist.items(), after that it worked.
An alternative.
cointypes = (100, 10, 5, 1, 0.5)
needed = {}
def coins(fin):
cur = fin
for c in cointypes:
v = int(cur / c)
if v > 0:
needed[c] = v
cur -= v * c
if __name__ == '__main__':
coins(51)
print needed
coins(127)
print needed
More information about the Python-list
mailing list