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’]