Skip to content

Instantly share code, notes, and snippets.

@harrytallbelt
Created April 14, 2021 13:28
Show Gist options
  • Save harrytallbelt/ba2c60248e3b490d8ce9f8a998946bf1 to your computer and use it in GitHub Desktop.
Save harrytallbelt/ba2c60248e3b490d8ce9f8a998946bf1 to your computer and use it in GitHub Desktop.
Excel-like row index to letter code conversion
import math
# 1, 2, 3, .. 26, 27, ... -> 'a', 'b', 'c', .. 'z', 'aa', ...
def to_row_code(row_index):
prefix = ''
if row_index > 26:
prefix = to_row_code(math.ceil((row_index - 26) / 26))
return prefix + chr(ord('a') + (row_index - 1) % 26)
# 'a', 'b', 'c', .. 'z', 'aa', ... -> 1, 2, 3, .. 26, 27, ...
def to_row_index(row_code):
res = ord(row_code[-1]) - ord('a') + 1
if len(row_code) > 1:
res += to_row_index(row_code[:-1]) * 26
return res
# test
print(all(i+1 == to_row_index(to_row_code(i+1)) for i in range(1000000)))
# I feel these two were much harder than they had any right to be.
# I thought this would be a simple conversion to and from base 26, but nope.
# It's like base 26, but with no digit for 0, and with a digit for 26.
# Anyway, in the end I solved these recursively, which means I kind of
# still have no intuition on how this works, but I'm confident that it does.
#
# P.S. The code counts on you to make sure its inputs are in correct format,
# so don't you dare betray its trust.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment