我正在尝试获取字符串的所有字母大小写排列,并将它们添加到一个这样的列表中:
allperm('an') should produce:
['an', 'aN', 'An', 'AN']
但是我的输出是多个列表:
['a', 'n']
['a', 'N']
这是我当前的代码
def allperm(password):
n = len(password)
#2^n permuations
max = 1 << n
#lowercase password (base)
password = password.lower()
#get all permutations
for i in range(max):
perm = [k for k in password]
for j in range(n):
if (((i >> j) & 1) == 1):
perm[j] = password[j].upper()
#add to list
temp = ""
for i in perm:
temp += i
return(temp)
答案 0 :(得分:3)
您可以用大写字母zip
密码的小写字母,并将其传递给itertools.product
以生成所需的排列:
from itertools import product
def allperm(password):
return list(map(''.join, product(*zip(password.lower(), password.upper()))))
使allperm('an')
返回:
['an', 'aN', 'An', 'AN']