0

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.

Sssssuppp
  • 683
  • 1
  • 7
  • 29
  • 6
    That is logical, since with `del` you change the *state* of the list, whereas with `chose = chosen[:-1]`, you create a *new* list. This thus means that references to the old list, still refer to a non-modified list. – Willem Van Onsem Jun 19 '19 at 17:03
  • Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Devesh Kumar Singh Jun 19 '19 at 17:04
  • 2
    Your code uses a mutable default value for a parameter (namely, an empty list for the `chosen` parameter). [This usually is a bad idea](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument). It would be better to use `None` as the default parameter, and replace it with an empty list. This matters if your function is called multiple times using the default parameter. – Rory Daulton Jun 19 '19 at 17:21

0 Answers0