Last active
January 9, 2025 23:09
-
-
Save mara004/ab9b0de41e9b0ff0e6b41b40b0ade6ef to your computer and use it in GitHub Desktop.
Enumerate data using letters rather than numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# SPDX-FileCopyrightText: 2024 geisserml <[email protected]> | |
# SPDX-License-Identifier: MPL-2.0 | |
from string import ascii_uppercase as ALPHABET | |
N_CHARS, ORD_A = len(ALPHABET), ord("A") # 26, 65 | |
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)] ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is basically the procedure used to tag spreadsheet columns, but you may find it useful for other cases as well.