Skip to content

Instantly share code, notes, and snippets.

@mara004
Last active September 13, 2024 15:07
Show Gist options
  • Save mara004/ab9b0de41e9b0ff0e6b41b40b0ade6ef to your computer and use it in GitHub Desktop.
Save mara004/ab9b0de41e9b0ff0e6b41b40b0ade6ef to your computer and use it in GitHub Desktop.
Enumerate data using letters rather than numbers
# SPDX-FileCopyrightText: 2024 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: MPL-2.0
from string import ascii_uppercase as ALPHABET
N_CHARS, ORD_A = 26, 65 # len(ALPHABET), ord("A")
def idx_to_label(i):
count, remainder = divmod(i, N_CHARS)
char = ALPHABET[remainder] # chr(remainder + ORD_A)
if count > 0:
return idx_to_label(count-1) + char
else:
return char
def label_to_idx(label):
prefix, char = label[:-1], label[-1]
i = ord(char) - ORD_A # ALPHABET.index(char)
if prefix:
return (label_to_idx(prefix) + 1) * N_CHARS + i
else:
return i
def get_label_maker():
i = 0
while True:
yield idx_to_label(i)
i += 1
LabelMaker = get_label_maker()
print( [next(LabelMaker) for _ in range(1000)] )
@mara004
Copy link
Author

mara004 commented Jul 21, 2024

This is basically the procedure used to tag spreadsheet columns, but you may find it useful for other cases as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment