1

I am working on a software problem and I found myself needing to convert a 2-letter string to a 3-digit number. We're talking about English alphabet only (26 letters).

So essentially I need to convert something like AA, AR, ZF, ZZ etc. to a number in the range 0-999. We have 676 combinations of letters and 1000 numbers, so the range is covered. Now, I could just write up a map manually, saying that AA = 1, AB = 2 etc., but I was wondering if maybe there is a better, more "mathematical" or "logical" solution to this. The order of numbers is of course not relevant, as long as the conversion from letters to numbers is unique and always yields the same results.

The conversion should work both ways (from letters to numbers and from numbers to letters).

Does anyone have an idea? Thanks a lot

furry12
  • 902
  • 1
  • 14
  • 31

2 Answers2

3

Treat A-Z as 1-26 in base 27, with 0 reserved for blanks.

E.g. 'CD' -> 3 * 27 + 4 = 85

85 -> 85 / 27, 85 % 27 = 3, 4 = C, D

Dave
  • 7,460
  • 3
  • 26
  • 39
  • ...or use base 26 and let 0 be 'A'. I prefer the former so strings with leading As are distinguished. – Dave Jun 05 '21 at 18:37
0

If you don’t have to use consecutive numbers, you can view a two-letter string as a 36-based number. So, you can just use the int function to convert it into an Integer.

int('AA', 36)  # 370
int('AB', 36)  # 371
#...
int('ZY', 36)  #  1294
int('ZZ', 36)  #  1295

As for how to convert the number back to a string, you can refer to the method on How to convert an integer to a string in any base?

@furry12 because the diff between the first number and the last one is 1295-370=925<999. It is quite lucky, so you can minus every number for like 300, the results will be in the range of 0-999

def str2num(s):
  return int(s, 36) - 300

print(str2num('AA')) # 70
print(str2num('ZZ')) # 995

Community
  • 1
  • 1
zenwalk
  • 26
  • 5
  • thanks for answering! This would work great, but for "higher" letters it goes out of bounds (for ZZ the result is 1295, and the range I need is 0-999) – furry12 Jun 05 '21 at 18:19