Darryl Hebbes
Darryl Hebbes

Reputation: 1028

How to see possible combinations of a given number in python

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?

Upvotes: 1

Views: 586

Answers (5)

Juanjo Conti
Juanjo Conti

Reputation: 30063

See the product generator.

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python.

The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python

.

Upvotes: 0

Luiz C.
Luiz C.

Reputation: 776

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

Upvotes: 1

remosu
remosu

Reputation: 5119

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

Upvotes: 1

Dmitry Kochkin
Dmitry Kochkin

Reputation: 993

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)

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319929

Example is in the itertools docs:

>>> import itertools
>>> for i in itertools.product(range(2), repeat=4):
    print(i)

Upvotes: 7

Related Questions