Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Every possible letter combination

Tags:

python

What's the most efficient way at producing every possible letter combination of the alphabet?

E.g. a,b,c,d,e...z,aa,ab,ac,ad,ae... ect

I've written a code that successfully produces this result but I feel like it's too inefficient at producing the desired result.

Any ideas?

I've also tried to explain what i've done

#import module time
import time

#set starting variable "gen", make gen list.
gen =''
gen = list(gen)

#expermintal alphabet, not actually used
alpha ='abcdefghijklmnopqrstuvwxyz'
alpha = list(alpha)

#Approx. on time taken to complete x letters
useless_value = raw_input("Press Enter to continue...")

print "How many letters would you like to start at?"
useless_value = input("> ")

gen = gen*useless_value

#start time for function
start_time= time.time()

try:
    gen[-1]
except IndexError:
    print "INVALID LETTER RANGE"
    print "DEFAULT LETTERS USED (1)"
    gen = 'a'
    gen = list(gen)



#function loop (will never break)
x=1
while True:

    #print raw string of gen
    print "".join(gen)

    #since infinite loop within same function, variables have to be reset
    #thus oh = 0 is reseting for later use
    oh = 0

    #change a to b, b to c... ect. Will only make one change
    if gen[-1] =='a':
        gen[-1] ='b'
    elif gen[-1] =='b':
        gen[-1] ='c'
    elif gen[-1] =='c':
        gen[-1] ='d'
    elif gen[-1] =='d':
        gen[-1] ='e'
    elif gen[-1] =='e':
        gen[-1] ='f'
    elif gen[-1] =='f':
        gen[-1] ='g'
    elif gen[-1] =='g':
        gen[-1] ='h'
    elif gen[-1] =='h':
        gen[-1] ='i'
    elif gen[-1] =='i':
        gen[-1] ='j'
    elif gen[-1] =='j':
        gen[-1] ='k'
    elif gen[-1] =='k':
        gen[-1] ='l'
    elif gen[-1] =='l':
        gen[-1] ='m'
    elif gen[-1] =='m':
        gen[-1] ='n'
    elif gen[-1] =='n':
        gen[-1] ='o'
    elif gen[-1] =='o':
        gen[-1] ='p'
    elif gen[-1] =='p':
        gen[-1] ='q'
    elif gen[-1] =='q':
        gen[-1] ='r'
    elif gen[-1] =='r':
        gen[-1] ='s'
    elif gen[-1] =='s':
        gen[-1] ='t'
    elif gen[-1] =='t':
        gen[-1] ='u'
    elif gen[-1] =='u':
        gen[-1] ='v'
    elif gen[-1] =='v':
        gen[-1] ='w'
    elif gen[-1] =='w':
        gen[-1] ='x'
    elif gen[-1] =='x':
        gen[-1] ='y'

    #if 'y' changes to 'z'. variable 'oh' is set to '1'.
    # This is so it doesn't enter unwanted equations
    elif gen[-1] =='y':
        gen[-1] ='z'
        oh = 1

    #if last string = 'z'
    #Checks max length of gen through [-1,-2].. ect
    if gen[-1] =='z':

        #reset s
        s = 0
        x=1
        while True:

            try:
                s
            except NameError:
                s = -1
            s = s-1

            try:
                gen[s]
            except IndexError:
                s = s+1
                break

    #s = the amount that gen cannot be
    #Therefore s+1 == max

    #resets values because of loop
    d= 0
    q= 0

    #this infinite loop checks the string to see if all string values = 'z'
    #if it does it will change all values to 'a' then add 'a'

    x=1
    while True:

        #useless piece of code #1 
        try:
            d
        except NameError:
            d = 0

        #useful
        d = d-1


        try:
            gen[d]
        except IndexError:
            break

        #if d value == 'z' it will continue, otherwise break from loop
        if gen[d] =='z':


            #if the max == the d value that means all values have been checked
            #and = 'z'. Otherwise it would've already broken the loop
            if s == d:

                x=1
                while True:


                    #if oh == 1 which was set from y changing to z
                    # it will not continue
                    #this is so that if 'zy' changes to 'zz' in the first
                    #loop it will not change to 'aaa' while still in the loop
                    # this is so it prints 'zz' and doesn't skip this
                    #This is important to assure all possible combinations are printed

                    if oh == 1:
                        break
                    else:
                        pass


                    #useless q already set to 0

                    try:
                        q
                    except NameError:
                        q = 0

                    #sets individually all values of 'z' to 'a'
                    q= q-1
                    try:
                        gen[q] ='a'

                    #then when q cannot exist, adds an 'a'
                    except IndexError:
                        gen = gen + ['a']

                        #sets oh = 1, just in case. most likely useless again
                        oh = 1
                        #prints time taken to complete amount of letters
                        print "Completed", ((len(gen))-1), "letters in", ((time.time() - start_time) /60), "minutes."
                        break

            else:
                continue


        else:
            break


    #if the last value = 'z' it will find the next non 'z' value and make all
    #values after it = 'a'. e.g. you have abczezzz
    # it will check find the 'e' and change that 'e' to a 'f'
    # then it will change all the z's after it to a's
    # so final would be - abczfaaa

    m = -1            
    if gen[-1] =='z':


        x=1
        while True:

            if oh == 1:
                break
            else:
                pass


            m = m -1
            if gen[m] =='a':
                gen[m] ='b'
                gen[(m+1):] = ('a')*(-(m+1))
                break

            elif gen[m] =='b':
                gen[m] ='c'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='c':
                gen[m] ='d'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='d':
                gen[m] ='e'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='e':
                gen[m] ='f'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='f':
                gen[m] ='g'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='g':
                gen[m] ='h'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='h':
                gen[m] ='i'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='i':
                gen[m] ='j'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='j':
                gen[m] ='k'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='k':
                gen[m] ='l'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='l':
                gen[m] ='m'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='m':
                gen[m] ='n'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='n':
                gen[m] ='o'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='o':
                gen[m] ='p'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='p':
                gen[m] ='q'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='q':
                gen[m] ='r'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='r':
                gen[m] ='s'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='s':
                gen[m] ='t'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='t':
                gen[m] ='u'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='u':
                gen[m] ='v'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='v':
                gen[m] ='w'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='w':
                gen[m] ='x'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='x':
                gen[m] ='y'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='y':
                gen[m] ='z'
                gen[(m+1):] = ('a')*(-(m+1))
                break
            elif gen[m] =='z':
                continue
like image 520
Kyle Pellerin Avatar asked Dec 08 '25 18:12

Kyle Pellerin


1 Answers

Use itertools.product() to create combinations of letters:

from string import ascii_lowercase
from itertools import product

for length in range(minimum_length, maximum_length + 1):
    for combo in product(ascii_lowercase, repeat=length):
        print ''.join(combo)

Take into account that the number of combinations produced grows exponentially with the length parameter.

Demo:

>>> minimum_length, maximum_length = 1, 2
>>> for length in range(minimum_length, maximum_length + 1):
...     for combo in product(ascii_lowercase, repeat=length):
...         print ''.join(combo)
... 
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
aa
ab
ac
ad
ae
af
ag
ah
ai
aj
ak
al
am
an
ao
ap
aq
ar
as
at
au
av
aw
ax
ay
az
ba
bb
bc
bd
be
bf
bg
bh
bi
bj
bk
bl
bm
bn
bo
bp
bq
br
bs
bt
bu
bv
bw
bx
by
bz
ca
cb
cc
cd
ce
cf
cg
ch
ci
cj
ck
cl
cm
cn
co
cp
cq
cr
cs
ct
cu
cv
cw
cx
cy
cz
da
db
dc
dd
de
df
dg
dh
di
dj
dk
dl
dm
dn
do
dp
dq
dr
ds
dt
du
dv
dw
dx
dy
dz
ea
eb
ec
ed
ee
ef
eg
eh
ei
ej
ek
el
em
en
eo
ep
eq
er
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
si
sj
sk
sl
sm
sn
so
sp
sq
sr
ss
st
su
sv
sw
sx
sy
sz
ta
tb
tc
td
te
tf
tg
th
ti
tj
tk
tl
tm
tn
to
tp
tq
tr
ts
tt
tu
tv
tw
tx
ty
tz
ua
ub
uc
ud
ue
uf
ug
uh
ui
uj
uk
ul
um
un
uo
up
uq
ur
us
ut
uu
uv
uw
ux
uy
uz
va
vb
vc
vd
ve
vf
vg
vh
vi
vj
vk
vl
vm
vn
vo
vp
vq
vr
vs
vt
vu
vv
vw
vx
vy
vz
wa
wb
wc
wd
we
wf
wg
wh
wi
wj
wk
wl
wm
wn
wo
wp
wq
wr
ws
wt
wu
wv
ww
wx
wy
wz
xa
xb
xc
xd
xe
xf
xg
xh
xi
xj
xk
xl
xm
xn
xo
xp
xq
xr
xs
xt
xu
xv
xw
xx
xy
xz
ya
yb
yc
yd
ye
yf
yg
yh
yi
yj
yk
yl
ym
yn
yo
yp
yq
yr
ys
yt
yu
yv
yw
yx
yy
yz
za
zb
zc
zd
ze
zf
zg
zh
zi
zj
zk
zl
zm
zn
zo
zp
zq
zr
zs
zt
zu
zv
zw
zx
zy
zz
like image 160
Martijn Pieters Avatar answered Dec 11 '25 08:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!