I was messing around with base conversion between decimal and Base26 (alphabet) with no 0th case because I needed it for the Google Sheets API in order to find specific cell values from a 3 dimensional list of all of the entered cell values on a spreadsheet. Remember that with spreadsheets, the columns are counted with no 0th case and A == 1 Z == 26 BA == 53.
Some test cases for conversion between the two bases would be
"zyz" == 18252, "aa" == 27, "zz" == 702
When I went to go write the code, I looked for simple solutions, but could not find anything using recursion so I wrote this in Python:
def base10ToBase26Letter(num):
''' Converts any positive integer to Base26(letters only) with no 0th
case. Useful for applications such as spreadsheet columns to determine which
Letterset goes with a positive integer.
'''
if num <= 0:
return ""
elif num <= 26:
return chr(96+num)
else:
return base10ToBase26Letter(int((num-1)/26))+chr(97+(num-1)%26)
def base26LetterToBase10(string):
''' Converts a string from Base26(letters only) with no 0th case to a positive
integer. Useful for figuring out column numbers from letters so that they can
be called from a list.
'''
string = string.lower()
if string == " " or len(string) == 0:
return 0
if len(string) == 1:
return ord(string)-96
else:
return base26LetterToBase10(string[1:])+(26**(len(string)-1))*(ord(string[0])-96)
I am aware that the first function outputs lowercase letters which can be bypassed by using base10ToBase26Letter(num).upper().
I used this to test the consistency of the values being output:
for x in range(0,100000):
if x == base26LetterToBase10(base10ToBase26Letter(x)):
print(x)
- Is recursion the best way to approach this problem efficiently, or should I be looking for something else?
- If I were to look at readability, is this way the easiest to read?
- Does this problem have a shorter solution?
- It seems that after about 11 letter digits, this program is no longer accurate, is there a way to make the functions accurate further? (Even if such numbers will never be used in a spreadsheet)
(A:1)is actually(1:1)programmaticly. \$\endgroup\$