Loops 一次进行Python置换
我写了嵌套循环,给我所有可能的字母排列,每次取4个字母Loops 一次进行Python置换,loops,python-3.x,recursion,permutation,Loops,Python 3.x,Recursion,Permutation,我写了嵌套循环,给我所有可能的字母排列,每次取4个字母 def permutation(): import string alphabet = string.ascii_lowercase perm = [] for item1 in alphabet: for item2 in alphabet: for item3 in alphabet: for item4 in alphabet
def permutation():
import string
alphabet = string.ascii_lowercase
perm = []
for item1 in alphabet:
for item2 in alphabet:
for item3 in alphabet:
for item4 in alphabet:
perm += [item1 + item2 + item3 + item4]
return perm
所以,当我这么做的时候
permutation()
我明白了
虽然这解决了我的特殊问题(4位数排列),但它不是一个好的解决方案。此外,如果我想做一个n位数的排列(比如说,10位数),嵌套循环将是一团糟
所以,我想你可以告诉我如何实现这个嵌套循环作为某种函数,使用递归或类似的方法
顺便说一句,我知道在这个特殊问题(4位置换)中,我可以使用python库:
def permutation():
from itertools import product
import string
alphabet = string.ascii_lowercase
perm = [ ''.join(p) for p in list(product(list(alphabet),repeat = 4)) ]
return perm
这就是我在现实生活中会用到的,但这里我试图找出一次取n个字母的字母排列算法。首先,将其分解为递归的两个基本点:退化步骤(最终条件)和递归步骤。这里,我们的最后一个条件是当我们需要长度为1的字符串时返回字母表
def permutation():
import string
alphabet = string.ascii_lowercase
perm = []
for item1 in alphabet:
for item2 in alphabet:
for item3 in alphabet:
for item4 in alphabet:
perm += [item1 + item2 + item3 + item4]
return perm
对于较长的字符串(长度为n),在字母表的每个字母前加上长度为n-1的所有排列
import string
alphabet = string.ascii_lowercase
def permutation(n):
return [c for c in alphabet] if n == 1 \
else [c + n_perm for c in alphabet for n_perm in permutation(n-1)]
print permutation(1)
print permutation(2)
如果你想进行N位数的排列(比如10位数),我有两种方法: 1) 将重复10分为5+5(或3+3+4): 2) 只需选择重复10次,如:
from itertools import product
import string
alphabet = string.ascii_lowercase
def permutation( repeat):
for p in product(list(alphabet), repeat=repeat):
yield ''.join(p)
for word in permutation (10): print word
具有等效的非lib Python代码。这就是您想要的吗?仅供参考,为了快速/简单起见,您应该在
itertools.product
代码中删除所有不必要的列表。您只需执行返回列表(map(''.join,product(string.ascii_小写,repeat=4))
;您在字母表
和产品
周围添加的列表
调用只是强制执行了无意义的中间列表
调用(尤其是包装产品
,因为这些输出元组
可以立即字符串化,并且峰值内存使用率将大大降低)。如果先循环递归结果,然后循环字母表(也就是说,在第二个生成器表达式中反转for
循环的顺序),则会获得更好的性能。
from itertools import product
import string
alphabet = string.ascii_lowercase
def permutation( repeat):
for p in product(list(alphabet), repeat=repeat):
yield ''.join(p)
for word in permutation (10): print word