Reputation: 121
I have a need to create a lookup table where A=10 and Z=35(B=11, C=12 and so on), what's the easiest way to accomplish this in python? I know there must be a very easy way to do it, just can't seem to find it.
Upvotes: 3
Views: 22355
Reputation: 838086
For a lookup table you can use a dict
:
d = { 'A' : 10, 'Z' : 35 } # etc..
However in this case it seems there is a simple logical rule for calculating the result so instead of a lookup table you could just use a function with some simple arithmetic:
def letterToNumber(c):
if not 'A' <= c <= 'Z':
raise ValueError('invalid character: ' + c)
return ord(c) - ord('A') + 10
def numberToLetter(x):
if not 10 <= x <= 35:
raise ValueError('invalid number: ' + x)
return chr(x - 10 + ord('A'))
Upvotes: 11
Reputation: 8701
I would go with the straightforward approach:
import string
def make_lookup_table():
"make a lookup table where 'A' -> 10, 'B' -> 11, ..., 'Z' -> 35"
lookup_table = {}
value = 10
for letter in string.uppercase[:26]:
lookup_table[letter] = value
value += 1
Upvotes: 0
Reputation: 133514
I agree that a lookup table is unnecessary but here is one
>>> import string
>>> x = dict(zip(string.uppercase[:26],range(10,36)))
>>> x['A']
10
>>> x['Z']
35
Upvotes: 4
Reputation: 601489
You don't need a look-up table – the expression
chr(c) - 54
(with c
beinig the upper-case character) will do the trick.
Upvotes: 7