Reputation: 89
while running this code its showing
digit(digit - 1, pref + str(0)) TypeError: unsupported operand type(s) for -: 'function' and 'int
def digit(n, pref):
if digit == 0:
print(pref)
else:
digit(digit - 1, pref + str(0))
digit(digit - 1, pref + str(1))
print(digit(3, ''))
Upvotes: 0
Views: 22
Reputation: 46921
this would be a simpler way:
def digit(n):
for i in range(1<<n):
print(f'{i:0{n}b}')
digit(3)
1<<n
is just 2
to the power of n
and then i print the number in binary with n binary places (filled by zero if necessary).
this could be shortened to
n=3
print('\n'.join(f'{i:0{n}b}' for i in range(1<<n)))
which would then generate your output.
Upvotes: 0
Reputation: 22794
You're treating digit
as if it was n
in some places in your code, replace it with n
and it'll work:
def digit(n, pref):
if n == 0:
print(pref)
else:
digit(n - 1, pref + '0') # just use '0', '1' instead of str(...)
digit(n - 1, pref + '1')
digit(3, '')
Output:
000
001
010
011
100
101
110
111
Note that use can also use itertools.product
for this task:
from itertools import product
print([''.join(p) for p in product('01', repeat=3)])
Output:
['000', '001', '010', '011', '100', '101', '110', '111']
Upvotes: 1