views:

107

answers:

5

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?

+7  A: 

Example is in the itertools docs:

>>> import itertools
>>> for i in itertools.product(range(2), repeat=4):
    print(i)
SilentGhost
Thanks very much everyone for the answers. Turns out what I was looking was a Gray Code. Gray code after Frank Gray, is a binary numeral system where two successive values differ in only one bit. WikiPedia
Darryl Hebbes
A: 

See the product generator.

Juanjo Conti
A: 
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)
Dmitry Kochkin
+1  A: 
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']
remosu
+1  A: 

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
Luiz C.
Thanks for the link, lots of info on generators and combinations that I needed elsewhere.
Darryl Hebbes