0

I am generating all binary strings of a given length and am trying to store them in a list which I am having trouble with. Here is the code:

def generateAllBinaryStrings(n, arr, l, i):  

    if i == n: 
        l.append(arr) 
        print(arr)
        return

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

    arr[i] = 1
    generateAllBinaryStrings(n, arr, l, i + 1)  

    return l

n = 3
l = []  
arr = [None] * n 
generateAllBinaryStrings(n, arr, l, 0)  

i.e. first creating all possible strings with the starting bit as 0 and then all strings with the starting bit as 1. arr stores strings and am trying to append them into a list l. The following print result is right for print(arr) statement but l is not correct. May I know where I went wrong?:

[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]

[[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
trickymaverick
  • 199
  • 1
  • 3
  • 8

1 Answers1

2

arr is a list which is mutable in Python. You modify the original object with each append and pop. Therefore you want to save/preserve the momentary state of arr when you append it to the output so you create a copy of it by slicing.

Corrected code:

def generateAllBinaryStrings(n, arr, l, i):  

    if i == n: 
        l.append(arr[:]) 
        print(arr[:])
        return

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

    arr[i] = 1
    generateAllBinaryStrings(n, arr, l, i + 1)  

    return l

n = 3
l = []  
arr = [None] * n 
generateAllBinaryStrings(n, arr, l, 0)  
Srishti Rawal
  • 594
  • 1
  • 5
  • 15