Reputation: 158
I am trying to write some recursive python code which prints every binary number of length n. The input of the function should only be n. This is my code so far:
def printAll(n):
result=[]
stringSoFar=''
def printAllrec(stringSoFar,n,result):
if n ==0:
result.append(stringSoFar)
if len(result) == (2):
return result
else:
printAllrec((stringSoFar+"0"),n-1,result)
printAllrec((stringSoFar+"1"),n-1,result)
return printAllrec(stringSoFar,n,result)
print(printAll(2))
However, this code keeps returning 'None'. I don't understand why it won't work. Any tips would be greatly appreciated.
Upvotes: 1
Views: 1740
Reputation: 42139
Using a recursive generator could make the code much more compact. You just need to take every result from n-1 and append a "0" and a "1".
def allBits(n):
if n: yield from ( bits+bit for bits in allBits(n-1) for bit in ("0","1") )
else: yield ""
for bits in allBits(3):print(bits)
000
001
010
011
100
101
110
111
Upvotes: 0
Reputation: 155604
Your code doesn't need more return
s, it needs to return the right thing. printAllrec
doesn't use return values here, it justs modifies a list
provided to the top level printAllrec
call, which is delegated to the child calls. But the top level function, printAll
, needs to return that list
, not the garbage return from the internal recursive function. Just change:
def printAll(n):
...
return printAllrec(stringSoFar,n,result)
to:
def printAll(n):
...
printAllrec(stringSoFar,n,result)
return result # returns the actual list
and it works as expected.
Upvotes: 2