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. -- http://mail.python.org/mailman/listinfo/python-list