Python Define Recursive Function Bits N Generates Returns List Possible Bit Strings Length Q37135556

Python: Define a recursive function bits(n) that generates andreturns a list of all possible bit strings of length <= n thatstart with digit 1. No repetitions.

For example, bits(3) should return [1, 10, 11, 110, 111, 100,101]. Order doesn’t matter.


Answer


def bits(n, power = 0):

if power == pow(2, n):

return []

return [bin(power)[2:]] + bits(n,power+1)

print(bits(4))

# OUTPUT: [‘0’, ‘1’, ’10’, ’11’,’100′,’101′, ‘110’, ‘111’, ‘1000’, ‘1001’, ‘1010’, ‘1011’, ‘1100’,’1101′, ‘1110’, ‘1111’]

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.