Excel Columns


In [1]:
import string

In [197]:
def excel_column(n):
    alphabet = string.ascii_uppercase
    alphabet_len = len(alphabet)  # 26
    
    def convert(n):
        if n < alphabet_len:    
            return alphabet[n]
        else:
            mod = n % alphabet_len
            first = excel_column(int(n / alphabet_len))
            return first + convert(mod)
        
    # zero-indexed
    return convert(n - 1)

In [198]:
test_cases = [
    (1, 'A'),
    (27, 'AA'),
    (700, 'ZX'),
    (702, 'ZZ'),
    (703, 'AAA'),
    (729, 'ABA'),
    (740, 'ABL'),
    (486, 'RR'),
    (440, 'PX'),
    (378, 'NN'),
    (53, 'BA'),
    (1168, 'ARX'),
    (1454, 'BCX')
]

all([excel_column(input_) == expected
     for input_, expected in test_cases])


Out[198]:
True