S2Q1 · Convert Excel Column Name to 1-Based Index¶
⚡ Quick Reference
Function: excel_index(column: str) -> int
Core idea: treat the column name as a base-26 number where A=1, B=2, …, Z=26.
def excel_index(column: str) -> int:
result = 0
for char in column:
result = result * 26 + (ord(char) - ord('A') + 1)
return result
Key rules:
- A=1, B=2, …, Z=26 (not 0-based)
- Each character shifts the running total left by one base-26 place
- ord(char) - ord('A') + 1 converts a letter to its 1-based value
Problem Statement¶
Problem
Write a function excel_index(column) that converts an Excel column name like "A", "Z", "AA", "AB", "ZZZ" to its corresponding 1-based integer index.
Examples:
"A"
1
"Z"
26
"AA"
27
"AB"
28
Understanding the problem¶
Excel columns follow a bijective base-26 system -digits are 1 to 26 (A–Z), with no zero digit.
A = 1
Z = 26
AA = 26×1 + 1 = 27
AB = 26×1 + 2 = 28
AZ = 26×1 + 26 = 52
ZZ = 26×26 + 26 = 702
AAA = 26²×1 + 26×1 + 1 = 703
The algorithm processes each character left to right, multiplying the running total by 26 and adding the current digit -this is Horner's method applied to base-26:
ord(char) - ord('A') + 1
ord('A') = 65, so ord(char) - 65 + 1 maps A→1, B→2, ..., Z→26. The +1 is crucial -without it A=0 breaks the bijective numbering.
Tracing key examples¶
"AA" → 27:
"ZZ" → 702:
"AAA" → 703:
result = 0
'A': result = 0 * 26 + 1 = 1
'A': result = 1 * 26 + 1 = 27
'A': result = 27 * 26 + 1 = 703
Solution approaches¶
from functools import reduce
def excel_index(column: str) -> int:
return reduce(lambda acc, c: acc * 26 + (ord(c) - ord('A') + 1), column, 0)
reduce applies Horner's method functionally. Starting value is 0.
Key takeaways¶
Bijective base-26 -digits are 1 to 26
Unlike standard base-26 (digits 0–25), Excel columns use 1–26. There is no zero column. This is why A=1 not A=0, and why AA=27 not AA=26.
Horner's method for base conversion
result = result * base + digit processes digits left to right without computing powers. Same algorithm used for polynomial evaluation -applies to any base.
ord(c) - ord('A') + 1
Maps 'A'→1, 'B'→2, ..., 'Z'→26. Using ord('A') instead of the magic number 65 makes intent clear and avoids off-by-one errors.