2011-06-08 46 views
0

我需要編寫生成器生成所有可能的8個符號字符串。 從符號的排列是這樣的:生成所有可能的8個符號字符串。蠻力8符號密碼。 python

leters = ['1','2','3','4','5','6','7','8','9','0','q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'] 

骨架看起來是這樣的:

def generator(): 
    """ 
    here algorithm 
    """ 
    yield string 

猜想這樣['00000001','00000002','00000003', ......'mmmmmmmm']

+1

只是一個建議,使用一臺發電機的這一點,因爲你將處理超過2萬億的元素。 'itertools.permutations('abcdefgh ...',8)' – gahooa 2011-06-08 18:32:03

+0

排列不會給你帶有重複元素的結果,例如任何帶有兩個或多個0的密碼。 – Cosmologicon 2011-06-08 18:37:03

回答

6

itertools.combinations()itertools.combinations_with_replacement()返回發電機

>>> letters = ['a', 'b', 'c'] 
>>> from itertools import combinations 

我使用在實施例print()來說明輸出。用yield替代它,得到一個發生器。

>>> for c in combinations(letters, 2): 
     print(c) 
... 
('a', 'b') 
('a', 'c') 
('b', 'c') 

>>> for c in combinations(letters, 2): 
     print(''.join(c)) 
... 
ab 
ac 
bc 
>>> 

>>> for c in itertools.combinations_with_replacement(letters, 2): 
     print(''.join(c)) 
... 
aa 
ab 
ac 
bb 
bc 
cc 

如果蠻力它包含英文字母和數字組成的所有8個字母組成的密碼,你正在尋找遍歷〜2.8萬億串

編輯 假如你不小心知道有沒有重複元素,使用permutations

>>> for c in itertools.permutations(letters, 2): 
     print(''.join(c)) 
... 
ab 
ac 
ba 
bc 
ca 
cb 

這給你兩個ABBA

對於最普通的蠻力順序使用itertools.product()在Cosmologicon的解決方案

+0

這隻會給你字眼的字典順序,不是嗎?我沒有在名單上看到「ba」。 – Cosmologicon 2011-06-08 18:47:17

+0

這是不正確的。你想'itertools.product' – 2014-06-11 15:34:21

6
itertools.product(leters, repeat=8) 

編輯返回列表:把它給你的字符串而不是元組:

def generator(leters): 
    a = itertools.product(leters,repeat=3) 
    while a: 
     yield "".join(a.next()) 
2
import itertools 
itertools.combinations_with_replacement(leters, 8) 

順便說一下,字母有兩個T字母。

+0

這需要多少時間才能完成? – RetroCode 2016-10-14 19:54:39

+0

@retrocode len(leters)** 8 *處理一個組合的時間。 – 2016-10-14 23:33:15