So, I was trying this backtracking problem where I had to find all the possible outcomes of rolling n
dices
My backtracking code looks like this
def dicRoll(n, chosen = []):
if n==0:
print(chosen)
else:
for i in range(1,7):
chosen.append(i)
dicRoll(n-1, chosen)
del chosen[-1]
This seems to work perfectly fine! But as soon as I replace del chosen[-1]
with chosen = chosen[:-1]
things go wrong!
Dysfunctional solution:
def dicRoll(n, chosen = []):
if n==0:
print(chosen)
else:
for i in range(1,7):
chosen.append(i)
dicRoll(n-1, chosen)
chosen = chosen[:-1]
I thought both do the exact same thing. What is the difference between the usage of the two lines causing different behaviors? Can someone please explain. I searched on SO, but there was no answer to a question which answered specifically this.