Skip to content

Instantly share code, notes, and snippets.

@ricardodani
Created August 20, 2012 18:24
Show Gist options
  • Save ricardodani/3406435 to your computer and use it in GitHub Desktop.
Save ricardodani/3406435 to your computer and use it in GitHub Desktop.
letter collumn sheet letters to integer index value
#!/bin/env/python
# -*- coding: utf-8 -*-
# Author: Ricardo L. Dani
# E-mail: ricardodani@gmail.com
# Github: http://github.com/ricardodani
'''
Utility functions for spreadshett manipulation.
'''
from math import pow
def cli(c):
'''
Collumn letter index, returns the index number of a letter collumn
value notation. Examples::
>>> cli('A')
>>> 0
>>> cli('B')
>>> 1
>>> cli('C')
>>> 2
...
>>> cli('Z')
>>> 25
>>> cli('AA')
>>> 26
>>> cli('AB')
>>> 27
'''
fl = ord('A') # first letter
ll = ord('Z') # last letter
rv = ll - fl # range value (26)
lt = ord(c[0]) - fl # letter in recursive context
if not (fl <= lt + fl <= ll): # validate the input
raise Exception('Invalid input (valid only letters inside A-Z).')
wt = len(c) -1 # weight of letter
return pow(rv, wt) * lt + lt + c[1:] if len(c) > 1 else 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment