算法:输入要返回的字母数,输入循环a-z,锁定第一个字符,循环第二个字符,锁定前两个,依此类推等等。输出看起来像a,b,c,d ...... aa,ab,ac,ad ... aaa,aab,aac ......等等。我是python的新手。我有一些东西在字母表中循环,但我的问题是锁定第一个并循环第二个,依此类推。
w = 'abcdefghijklmnopqrstuvwxyz'
n = input ("# of characters: ")
for a in range(0,n):
for i in w:
print i
答案 0 :(得分: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)
我认为这就是你正在寻找的东西
答案 1 :(得分:0)
为避免巨大的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