簡體   English   中英

如何在python中查看給定數字的可能組合

[英]How to see possible combinations of a given number in python

在Python中,我想查看一個數字的所有可能組合,但限制為0和1。

因此,例如,某些循環的結果將是:

0000
0001
0011
0111
1111
1000
and so on.

哪種python算法最適合呢?

示例在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']

您正在尋找k組合。 檢查這個出來。

您要查看的功能是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

請參閱產品生成器。

該模塊實現了許多迭代器構造塊,這些構造塊的靈感來自APL,Haskell和SML的構造。 每個都已經以適合Python的形式進行了重鑄。

該模塊標准化了一組快速的,內存有效的工具的核心集,這些工具本身或結合使用很有用。 它們共同構成了一個“迭代器代數”,從而可以用純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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM