0

I am trying to write a basic backtracking piece of code and have ran into an error with my list. I have created my list at the bottom just before calling the function, however I still get list assignment index out of range!

I have tried leaving the list empty by just saying arr = [] but nothing seems to work.

def printStrings(n, arr, i):
    if n == i:
        pass

    arr[i] = 0
    printStrings(n, arr, i+1)

    arr[i] = 1
    printStrings(n, arr, i+1)


if __name__ == "__main__":
    n = 4
    arr = [None] * n
    printStrings(n, arr, 0)

I am expecting the list to be initialized when i write arr = [None] * n but i guess its not creating a list with 4 index's. Please help. Thanks

Alex
  • 35
  • 3
  • 1
    Use `return`, not `pass`. – Ellisein Jun 04 '19 at 01:57
  • Thank you that worked, but can you please explain to me why the code that i wrote wouldnt work? Even if i put a simple print statement without the return it wouldn't work. – Alex Jun 04 '19 at 02:00
  • `pass` will simply ignore that block of code and move on to the next. `return` will exit the function by returning the value specified or `None` – C.Nivs Jun 04 '19 at 02:02

1 Answers1

0
if n == i:
    pass

Change pass to return.

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
  • Thank you that worked, but can you please explain to me why the code that i wrote wouldnt work? Even if i put a simple print statement without the return it wouldn't work. – Alex Jun 04 '19 at 02:00
  • ```n``` is the length of the array, and ```i``` is the index of an item in the array, starting at 0. If an array has length 4, then it's last element is ```i = 3```. In your code, if ```n``` == ```i```, then it's out of bounds. However, ```pass``` does absolutely nothing. It's a placeholder for "there's no code here". So, you perform that check, do nothing, then the function keeps going. – Michael Bianconi Jun 04 '19 at 02:05