简体   繁体   English

python 2.7单词生成器

[英]python 2.7 word generator

Algorithm: take input on how many letters to go back, for loop to loop az, lock the first character, loop the second character, lock the first two, loop the third, and so on and so forth. 算法:输入要返回的字母数,以循环循环az,锁定第一个字符,循环第二个字符,锁定前两个字符,循环第三个字符,依此类推。 The out put will look like a, b, c, d... aa, ab, ac, ad... aaa, aab, aac... and so on. 输出将看起来像a,b,c,d ... aa,ab,ac,ad ... aaa,aab,aac ...等等。 I am very new to python. 我是python的新手。 I have something that cycles through the alphabet, but my problem is to lock the first and cycle the second and so on. 我有一些循环遍历字母的内容,但是我的问题是锁定第一个而第二个循环,依此类推。

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

for a in range(0,n):
        for i in w:
                print i
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)

I think this is what you're looking for 我认为这就是您要寻找的

To avoid huge RAM requirements, use itertools.combinations to generate a single output at a time, handling the "locking" for you: 为了避免巨大的RAM需求,请使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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