ouldsmobile
ouldsmobile

Reputation: 121

python lookup table

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

Answers (4)

Mark Byers
Mark Byers

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

taleinat
taleinat

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

jamylak
jamylak

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

Sven Marnach
Sven Marnach

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

Related Questions