lsterzinger
lsterzinger

Reputation: 717

Infinity generation of ascii combinations

I currently have some code that looks like this:

def letter_sets():
    import string
    import itertools
    yield from string.ascii_letters
    for a, b in itertools.combinations(string.ascii_letters, 2):
        yield a + b
    for a, b, c in itertools.combinations(string.ascii_letters, 3):
        yield a + b + c

Which generates a list of ascii characters, first single, then double, etc [a,b,c...X,Y,Z,aa,ab,ac,..ZX.ZY,ZZ...]. However, this is capped at 23478 items.

Is there a way to create a similar combination that can theoretically go on forever without needing to code a new rank?

Upvotes: 1

Views: 292

Answers (3)

Alex
Alex

Reputation: 7065

Something like this. You can pass a number to max_str_length to stop the iterator once it's generated the strings of that length or call break in the for loop.

import string
import itertools


def letter_sets(alphabet, start=1, max_str_length=float("inf")):
    while start <= max_str_length:
        for group in itertools.combinations(alphabet, start):
            yield "".join(group)
        start += 1

for s in letter_sets(string.ascii_letters):
    print(s)

Upvotes: 1

0x5453
0x5453

Reputation: 13589

I believe this is what you want, using itertools.count to generate an infinite sequence of lengths:

import string
import itertools

def letter_sets():
    for length in itertools.count(1):
        for letters in itertools.combinations(string.ascii_letters, length):
            yield ''.join(letters)

Upvotes: 3

Kyle Parsons
Kyle Parsons

Reputation: 1525

def letter_sets():
    import string
    import itertools
    i = 0
    while True:
        yield from (''.join(comb) for comb in itertools.combinations(string.ascii_letters, i))
        i += 1

Upvotes: 0

Related Questions