Hi, in Python I wanting see all the possible combination's of a number, but limiting to 0's and 1's...
So for example the result of some loop would be:
0000
0001
0011
0111
1111
1000
and so on.
What python algorithm would best suite this?
Hi, in Python I wanting see all the possible combination's of a number, but limiting to 0's and 1's...
So for example the result of some loop would be:
0000
0001
0011
0111
1111
1000
and so on.
What python algorithm would best suite this?
Example is in the itertools
docs:
>>> import itertools
>>> for i in itertools.product(range(2), repeat=4):
print(i)
def print_all_combinations(max_value):
width = len('{0:0b}'.format(max_value))
format_string = '{0:0%db}' % width
for i in xrange(max_value):
print format_string.format(i)
def f(n):
if n==1:
return ['0', '1']
tmp = f(n-1)
return ['0'+v for v in tmp] + ['1'+v for v in tmp]
>>> f(4)
['0000',
'0001',
'0010',
'0011',
'0100',
'0101',
'0110',
'0111',
'1000',
'1001',
'1010',
'1011',
'1100',
'1101',
'1110',
'1111']
You're looking for k-combinations. Check this out.
The function you want to look at is xcombinations:
def xcombinations(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
for cc in xcombinations(items[:i]+items[i+1:],n-1):
yield [items[i]]+cc