Skip to content
Aditya Bhalsod
← Open Source
Open SourceBeginner

Combinatorial Growth and Lazy Iteration With itertools.product

A close reading of Bruteforce-Python, a 2020 learning script built on itertools.product, with the arithmetic for its 45.8 trillion strings and what I would fix today.

  • #python
  • #itertools
  • #lazy-iteration
  • #combinatorics
Contents
  1. One lazy iterator does the work
  2. Count the alphabet before trusting it
  3. What that costs in disk
  4. What the helper methods really do
  5. What I would fix today

Bruteforce-Python is a small learning experiment from 2020: one Python script that uses itertools.product to generate every fixed-length combination of letters and append them to CSV files. The README calls it an example written for fun. Despite the name, it does not attack anything. It only writes text files.

It is still worth a close read. Python can describe an enormous sequence without holding it in memory, but describing it is not the same as storing it. The comments at the end of the script warn about a very long run and very large files without saying how large. This post does the arithmetic.

One lazy iterator does the work

The core of the script is this loop in generate:

Python
for i in range(min_length, max_length + 1):
    product = itertools.product(
        "ABCDEFGHIJKLMNOPRSTUVWXYZabcdefghijklmnopqrstuvwxyz", repeat=i
    )
    self.filewrite(product)  # file writeing method

itertools.product does not build a list. It returns an iterator that produces one tuple of i characters each time it is asked, and keeps only its inputs and its current position. That is lazy iteration: the script never holds more than one combination at a time. Both class constants, MIN_LENGTH and MAX_LENGTH, are 8, so by default the loop runs once, with repeat=8.

Count the alphabet before trusting it

The string literal looks like the 52 ASCII letters. It is not. Count it and there are 51 characters: 26 lowercase and 25 uppercase. The sequence runs OPRST, so uppercase Q is missing. The commented-out copy just above has the same gap.

So the default run produces 51 ** 8 strings, which is 45,767,944,570,401: about 45.8 trillion. With all 52 letters it would be 53,459,728,531,456. One missing character removes 7,691,783,961,055 strings, about 14 percent, and nothing in the output would show it. Strings containing a Q are never generated.

What that costs in disk

filewrite puts one string on each line. Eight characters plus a newline is 9 bytes, so the full output is 45,767,944,570,401 times 9, or 411,911,501,133,609 bytes: about 412 TB in decimal units. (On Windows, text mode writes the newline as two bytes, which makes it about 458 TB.)

Length drives that number. The same calculation for other lengths:

LengthStringsDisk at one per line
46,765,20133.8 MB
617,596,287,801123.2 GB
8 (the default)45,767,944,570,401411.9 TB
10119,042,423,827,613,0011.31 EB

What the helper methods really do

Python
# more efficent and low memory use for this method
def grouper(self, iterable, fillvalue=None):
    args = [iter(iterable)]
    return itertools.zip_longest(*args, fillvalue=fillvalue)

# file write method
def filewrite(self, product):
    chunks_gen = self.grouper(product)
    for x in chunks_gen:
        file = open(x[0][0] + ".csv", "a")
        file.writelines(("".join(item) + "\n" for item in x if item))
        file.close()

This grouper matches the classic chunking recipe from the itertools documentation with one thing missing. The recipe takes a chunk size n and builds [iter(iterable)] * n, so zip_longest pulls n items into each tuple. Here the list holds the iterator once, so every "chunk" is a 1-tuple wrapping a single combination. The comment is half right: memory use is low, because everything is lazy, but nothing is grouped.

That explains x[0][0]: x[0] is the only combination in the chunk and x[0][0] is its first character. Each string goes to a file named after its leading letter, A.csv, B.csv and so on. On a case-sensitive file system that makes 51 files of 897,410,677,851 lines each, about 8 TB apiece. On Windows or a default macOS volume, where A.csv and a.csv are the same file, it makes 26.

It also means one open, one write and one close per string, 45.8 trillion times. itertools.product works like an odometer, with the rightmost position changing fastest, so the script reopens the same file 897 billion times in a row before the first letter moves on. The example in the script's trailing comment shows the leftmost character changing first, which is the wrong way round.

What I would fix today

Three things in the code:

  • Build the alphabet from string.ascii_letters instead of typing it. A missing letter raises no error. It just removes strings.
  • Open each file once. itertools.groupby on the first character gives one run per file, because product emits every string for one leading letter before the next. A chunk size in grouper alone would not do it: a chunk that crosses a letter boundary would land whole in the file named by its first string.
  • Keep the work out of __init__ and stop appending. With mode "a", a second run adds duplicates to the first run's files.

The bigger fix is to do the arithmetic first. For lengths up to 4 or 5 this script is a fine way to watch itertools.product work: five letters come to about 2 GB. At 8, the output should not be written at all. The iterator already is the compact form of the data.

Found this useful? Share it with your team.

Keep reading

More from Open Source and beyond