1

I'm trying to read each character from words in a list, and then assign a value to them based on each of the letters in that word. My code is stupidly long, and I'm convinced there must be a shorter way to do it...

    for c in tempWord:
        if(c == "A"):
            tempSum += 1
        elif(c == "B"):
            tempSum += 2
        elif(c == "C"):
            tempSum += 3
        elif(c == "D"):
            tempSum += 4
        elif(c == "E"):
            tempSum += 5
        elif(c == "F"):
            tempSum += 6
        elif(c == "G"):
            tempSum += 7
        elif(c == "H"):
            tempSum += 8
        elif(c == "I"):
            tempSum += 9
        elif(c == "J"):
            tempSum += 10
        elif(c == "K"):
            tempSum += 11
        elif(c == "L"):
            tempSum += 12
        elif(c == "M"):
            tempSum += 13
        elif(c == "N"):
            tempSum += 14
        elif(c == "O"):
            tempSum += 15
        elif(c == "P"):
            tempSum += 16
        elif(c == "Q"):
            tempSum += 17
        elif(c == "R"):
            tempSum += 18
        elif(c == "S"):
            tempSum += 19
        elif(c == "T"):
            tempSum += 20
        elif(c == "U"):
            tempSum += 21
        elif(c == "V"):
            tempSum += 22
        elif(c == "W"):
            tempSum += 23
        elif(c == "X"):
            tempSum += 24
        elif(c == "Y"):
            tempSum += 25
        elif(c == "Z"):
            tempSum += 26

This is probably a stupid question, but thanks anyway!

ApocalypticNut
  • 135
  • 1
  • 6
  • The answer below will do the job. Also, addition info here: http://stackoverflow.com/questions/227459/ascii-value-of-a-character-in-python – Joe Z Dec 19 '13 at 15:32

6 Answers6

6

Use ord to calculate the offset of the character from A.

A = ord('A')
for c in tempWord:
    if 'A' <= c <= 'Z':
        tempSum += ord(c) - A + 1

A = ord('A')
tempSum = sum(ord(c) - A + 1 for c in tempWord if 'A' <= c <= 'Z')
falsetru
  • 357,413
  • 63
  • 732
  • 636
1
if 'A'<=c<='Z':
    tempsum+=ord(c)-ord('A')+1
hcf
  • 148
  • 5
1

What about:

import string

def assign(word):
    return sum(string.uppercase.index(ch.upper())+1 for ch in word)

print assign('SIMPLE')
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
1

Well, the best advice for this problem is to create a dictionary associating letter to numbers:

d = {'A':1, 'B':2 ... }

and changing your if else nightmare with this:

tempSum += d[letter]

Now, by looking detailed at your example and the organization, it seems to be that the value to be summed is the position of upper case letters in the alphabet, so a pythonic way could be using the string module like this:

import string

tempSum += (string.uppercase.index(letter) + 1)

Hope this helps

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
0

I tend to make a dictionary. That should perform better than using .index on a list, because dict lookup is ~O(1), but list.index can take O(n) in the length of the list (say you're always looking up "Z", for example-- you have to scan the entire list.) It's not as short as using ord, but it's more robust.

Depending on how complex the mapping is, you may want to build it in many different ways. One would be:

>>> import string
>>> d = {c: i for i,c in enumerate(string.ascii_uppercase, 1)}
>>> d
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4, 'G': 7, 'F': 6, 'I': 9, 'H': 8, 'K': 11, 'J': 10, 'M': 13, 'L': 12, 'O': 15, 'N': 14, 'Q': 17, 'P': 16, 'S': 19, 'R': 18, 'U': 21, 'T': 20, 'W': 23, 'V': 22, 'Y': 25, 'X': 24, 'Z': 26}

after which:

>>> word = "INCONTROVERTIBLE"
>>> score = sum(d[c] for c in word)
>>> score
201

or, if you want to be more tolerant of missing letters, you can use the .get method with a default value of 0:

>>> word = "THIS IS A TEST"
>>> score = sum(d.get(c,0) for c in word)
>>> score
149
DSM
  • 342,061
  • 65
  • 592
  • 494
0

I know this is 5 years old, but it filled the gaps on what I was looking for, so I am sharing the function I made from it.

My goal was to turn Excel columns into numbers, so I could then feed them into a df.drop() function.

Here is the function I built, for up to 2 Chars only, but you could build a loop for infinite str lengths.

colNumbers = []

def letterTonumber(col):
    A = ord('A')
    tempSum = sum(ord(l) - A + 1 for l in col if 'A' <= l <='Z')

    return(tempSum)

def colParse(colNumbers, cols):
    for c in cols:
        if len(c) == 2:
            x=26*letterTonumber(c[0])
            y=letterTonumber(c[1])
            n=(x+y)-1
        else:
            n = letterTonumber(c)-1

        colNumbers.append(n)

cols = ['A','Z','AA','BB']
colParse(colNumbers, cols)

print(colNumbers)

>>> 0,25,26,53
Runawaygeek
  • 115
  • 3
  • 13