简体   繁体   中英

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?

Example is in the itertools docs :

>>> import itertools
>>> for i in itertools.product(range(2), repeat=4):
    print(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

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

.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM