Created
November 3, 2011 15:49
-
-
Save cockscomb/1336837 to your computer and use it in GitHub Desktop.
Convert mutually Excel’s column names to numbers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import string | |
import re | |
from functools import reduce | |
CHARS = string.ascii_uppercase | |
def number_to_char(number): | |
if number < 0: raise ValueError | |
result = '' | |
while number > 0: | |
number, remainder = divmod(number - 1, 26) | |
result = CHARS[remainder] + result | |
return result | |
def char_to_number(char): | |
if not re.match(r'^[A-Z]*$', char): raise ValueError | |
return reduce(lambda sum, c: sum * 26 + CHARS.index(c) + 1, char, 0) | |
input = 'XFD' | |
number = char_to_number(input) | |
char = number_to_char(number) | |
print("Input: {0} to Number: {1} to Char: {2}".format(input, number, char)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: UTF-8 | |
CHARS = ('A'..'Z').to_a | |
def number_to_char(number) | |
raise ArgumentError if number < 1 | |
result = '' | |
while number > 0 | |
number, remainder = (number - 1).divmod(26) | |
result.prepend(CHARS[remainder]) | |
end | |
result | |
end | |
def char_to_number(char) | |
raise ArgumentError unless char =~ /^[A-Z]*$/ | |
char.each_char.inject(0) { |sum, c| sum * 26 + CHARS.index(c) + 1 } | |
end | |
input = 'XFD' | |
number = char_to_number(input) | |
char = number_to_char(number) | |
puts "Input: #{input} to Number: #{number} to Char: #{char}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment