I was looking for Python “sequence generator” code earlier today. By that, I’m thinking of a method to increment an arbitrary string of letters and numbers in an orderly way.

I figured there should be code samples out there to make quick work of it, but it was more challenging to find something than expected. Part of it might be my weak conceptual grasp of the subject. Maybe I just lacked the necessary search terms. With the words I did have — sequence and generator — I got a lot of static since these terms describe basic Python concepts.

I finally resorted to crafting my own sequence generator. To you, Future Searcher, I hope it will be useful. It is easy enough to convert this into a function, which I did for my script. (Or maybe you’ll want an actual generator!) I won’t elaborate on it more. If you’re looking for this, you probably know everything you need to know.

(I’m releasing this into the public domain. Use the code freely and at your own risk.)

sequence_generator.py

#!/usr/bin/python3

import sys

if len(sys.argv) < 2:
    last_value = ' '
else:
    last_value = ' ' + sys.argv[1].strip()

next_value = ''

# alphabet: first character must repeat at end so we can detect digit rollover

# hex = '0123456789abcdef0'
# 36 chars = '0123456789abcdefghijklmnopqrstuvwxyz0'
# 62 chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0'
# 28 chars = '23456789BCDFGHJKMNPQRSTVWXYZ2'
#            (dropping 0, 1, and vowels to avoid confusion and actual words)

alphabet = '0123456789abcdefghijklmnopqrstuvwxyz0'

increment = True
for x in reversed(last_value):  # walk backwards, incrementing as necessary
    if x == ' ':                # reached the beginning
        if increment:           # all chars rolled over: grow a digit
            x = alphabet[0]     # create new leftmost "zero" to count from
        else:
            break               # we're done

    if increment:
        next_alphabet_idx = alphabet.find(x) + 1
        this_char = alphabet[next_alphabet_idx]
        if next_alphabet_idx + 1 < len(alphabet):
            increment = False   # we're done "rolling"
    else:
        this_char = x

    next_value = this_char + next_value  # building new value right to left
    # print(next_value.strip())

print('last value = ' + last_value.strip())
print('next value = ' + next_value)