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?
Asked
Active
Viewed 1,183 times
-6
-
6Can you share what you have tried so far? – cementblocks Sep 21 '20 at 14:03
-
Have you looked into [itertools.combinations](https://docs.python.org/3.8/library/itertools.html#itertools.combinations)? – rassar Sep 21 '20 at 14:05
-
See [this](https://stackoverflow.com/questions/7074051/what-is-the-best-way-to-generate-all-possible-three-letter-strings) – namgold Sep 21 '20 at 14:05
-
charses = 'abcdefghijklmnopqrstuvwxyz' listilist= [] for current in xrange(10): a = [i for i in your_list] for y in xrange(current): a = [x+i for i in charses for x in a] listilist= listilist+a – Tahalich Sep 21 '20 at 14:05
-
is there a way to do that without itertools? – Tahalich Sep 21 '20 at 14:05
-
3@Tahalich please updated in the question, not post in comment – namgold Sep 21 '20 at 14:06
-
1@Tahalich edit the question and show what you've tried there, not in comment – phuclv Sep 21 '20 at 14:06
3 Answers
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