Reputation: 23
I am trying to get all of the letter case permutations for a string and add them into one list like this:
allperm('an') should produce:
['an', 'aN', 'An', 'AN']
but my Output is multiple lists:
['a', 'n']
['a', 'N']
This is my current code
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)
Upvotes: 2
Views: 398
Reputation: 106946
You can zip
the lowercase characters of the password with the uppercase ones, and pass them to itertools.product
to generate the desired permutations:
from itertools import product
def allperm(password):
return list(map(''.join, product(*zip(password.lower(), password.upper()))))
so that allperm('an')
returns:
['an', 'aN', 'An', 'AN']
Upvotes: 4