oldboy
oldboy

Reputation: 5964

All Unique Alphabetical Combinations

It's been a while since I've used Python and needed to do something like this. But what I'd like to do is loop through every unique four-character alphabetical sequence. For example:

aaaa aaab ... aaaz ... abcd ... zzzz

import string
az = string.ascii_lowercase
for c1 in az:
  for c2 in az:
    for c3 in az:
      for c4 in az:
        print(c1 + c2 + c3 + c4)

Is there a more efficient and or prettier way to do this?

Upvotes: 0

Views: 123

Answers (2)

user2191247
user2191247

Reputation:

If you need to roll your own, then you can iterate from 0 to 26⁴ - 1, and convert to a number base 26 with your own digit translation.

def baseN(number, base, digits):
    return ((number == 0) and digits[0]) or (baseN(number // base, base, digits) + digits[number % base])

digits = "abcdefghijklmnopqrstuvwxyz"
base = len(digits)
length = 4

for number in range(base ** length):
    print((digits[0] * (length - 1) + baseN(number, base, digits))[-length:])

Upvotes: 0

Mark
Mark

Reputation: 92461

I think itertools.product() is what you are looking for. If you pass it string.ascii_lowercase and the number of characters you want, it should do the rest:

from itertools import product
import string
[''.join(s) for s in product(string.ascii_lowercase, repeat=4)]

--

['aaaa',
 'aaab',
 'aaac',
 'aaad',
 'aaae',
 'aaaf',
 'aaag',
 'aaah',
 'aaai',
 ...
 'zzzq',
 'zzzr',
 'zzzs',
 'zzzt',
 'zzzu',
 'zzzv',
 'zzzw',
 'zzzx',
 'zzzy',
 'zzzz']

Upvotes: 1

Related Questions