Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...
Example 1:
Input: "A" Output: 1
Example 2:
Input: "AB" Output: 28
Example 3:
Input: "ZY" Output: 701
Constraints:
1 <= s.length <= 7
s
consists only of uppercase English letters.s
is between "A" and "FXSHRXW".Source
def title_to_number(s):
def alpha_to_num(letter):
'''helper function'''
# match = {'A': 1, 'B': 2, 'C': 3} # Option 1: define a matching dictionary
# return match[letter]
return ord(letter) - ord('A') + 1 # Option 2: use ord()
result = 0
i = 0
for char in reversed(s):
result += alpha_to_num(char) * 26 ** i
i += 1
return result
from functools import reduce
def title_to_number(s):
'''variations of above'''
def alpha_to_num(letter):
'''helper function'''
return ord(letter) - ord('A') + 1
result = 0
# Option 1
for char, i in zip(reversed(s), range(len(s))):
result += alpha_to_num(char) * 26 ** i
# Option 2
for char in s:
result = result*26 + alpha_to_num(char)
# Option 3
# using reduce(function, iterable, initializer)
result = reduce(lambda result, x: result*26 + alpha_to_num(x), s, 0)
return result
title_to_number('A')
1
title_to_number('AB')
28
title_to_number('ZY')
701
title_to_number('FXSHRXW')
2147483647