2016-10-14 47 views
0

算法:輸入多少個字母返回,循環到循環az,鎖定第一個字符,循環第二個字符,鎖定前兩個,循環第三個,等等等等。輸出將看起來像a,b,c,d ... aa,ab,ac,ad ... aaa,aab,aac ...等等。我對python非常陌生。我有一些在字母表中循環的東西,但我的問題是鎖定第一個,然後循環第二個,等等。python 2.7字生成器

w = 'abcdefghijklmnopqrstuvwxyz' 
n = input ("# of characters: ") 

for a in range(0,n): 
     for i in w: 
       print i 
+0

您可以使用內置模塊嗎?特別是'itertools'會大大簡化這個過程。 – ShadowRanger

+0

我可以使用內置模塊。我很新,所以我不知道他們是什麼,或者每個人的能力。 – lineman2208

+1

然後,我會看看['itertools'](https://docs.python.org/2/library/itertools.html),特別是[組合函數](https://docs.python .ORG/2 /庫/ itertools.html#itertools.combinations)。對於記錄來說,將'tuple'這個函數的輸出轉換成'str'的​​一個生成器的一個有效方法是將它包裝起來,改變itertools.combinations(...)中的tupval [ :'to'for itertools.imap(''。join,itertools.combinations(...))中的strval:'所以你甚至不會看到'tuple';它們在製作時會轉換回「str」。 – ShadowRanger

回答

0
alphabet = 'abcdefghijklmnopqrstuvwxyz' 
l= [''] 
for i in range(input): 
    l = [letter + item for letter in alphabet for item in l] 
    for item in l: 
     print(item) 

我認爲這是你在找什麼

+0

注意:這涉及到存儲_huge_列表臨時對象。每個循環創建'len == i + 1'的'26 **(i + 1)''str',所以你需要在16 GB的RAM附近的某個地方長度爲6個字,400 GB左右處理長度爲7個字,長度爲8個時約11個TB。我強烈建議不要這樣做; CPU的工作足夠糟糕,但頁面抖動會使這真的很糟糕。 – ShadowRanger

+0

如果我將它從臨時文件轉換爲txt文件,該怎麼辦?這會重溫一些壓力嗎?所以,而不是打印保存到文件。 – lineman2208

0

爲了避免巨大的內存需求,使用itertools.combinations以每次生成一個單一的輸出,處理「鎖定」爲您提供:

from future_builtins import map # Not needed on Py3, only on Py2 
from itertools import combinations 

w = 'abcdefghijklmnopqrstuvwxyz' 
# Don't use input on Py2; it's an implicit eval, which is terrible 
# raw_input gets str, and you can explicitly convert to int 
n = int(raw_input("# of characters: ")) 

# You want 1-n inclusive on both ends, not 0-n exclusive at the end, so tweak range 
for wdlen in xrange(1, n+1): 
    # Generator based map with ''.join efficiently converts the tuples 
    # from combinations to str as you iterate 
    for wd in map(''.join, combinations(w, wdlen)): 
     print wd