-6

I need to find a way to brute-force from aaaa to zzzz using python (aaaa, aaab, aaac... zzzz). Similar to 0000 to 9999. Is there a "magical" way to do that using loops and lists?

Tahalich
  • 13
  • 5

3 Answers3

1

You can accomplish this succinctly with using itertools.product:

import itertools
import string

for elem in itertools.product(string.ascii_lowercase, repeat=5):
    ...

Here's a sample for the first 30 values yielded by this approach:

>>> values = itertools.product(string.ascii_lowercase, repeat=5)
>>> print(list(itertools.islice(values, 30)))
[
    ('a', 'a', 'a', 'a', 'a'), 
    ('a', 'a', 'a', 'a', 'b'), 
    ('a', 'a', 'a', 'a', 'c'), 
    # --Snip -- 
    ('a', 'a', 'a', 'a', 'x'), 
    ('a', 'a', 'a', 'a', 'y'), 
    ('a', 'a', 'a', 'a', 'z'), 
    ('a', 'a', 'a', 'b', 'a'), 
    ('a', 'a', 'a', 'b', 'b'), 
    ('a', 'a', 'a', 'b', 'c'), 
    ('a', 'a', 'a', 'b', 'd')
]

Note that there are 26**5 == 11881376 values in this sequence, so you probably don't want to store them all in a list. On my system, such a list it occupies roughly 100 MiB.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
0

This is a very "basic" example:

chars = 'abcdefghijklmnopqrstuvwxyz'
my_list = []

for c1 in chars:
    for c2 in chars:
        for c3 in chars:
            for c4 in chars:
                my_list.append(c1+c2+c3+c4)
                
print(my_list)
charbel
  • 471
  • 1
  • 5
  • 18
0

It's not easy to know what you consider "magical", but I don't see the magic in loops.
Here is one variation:

cs = 'abcdefghijklmnopqrstuvwxyz'
list(map(''.join, [(a,b,c,d) for a in cs for b in cs for c in cs for d in cs]))
molbdnilo
  • 64,751
  • 3
  • 43
  • 82