tags:

views:

214

answers:

9

How do i assign a numerical value to each uppercase letter, and then use it later via string and then add up the values.

EG.

A = 1, B = 2, C = 3 (etc..)

string = 'ABC'

Then return the answer 6 (in this case).

+5  A: 

You can use ord to get the ascii code, then subtract 64.

def codevalue(char):
    return ord(char) - ord('A')
recursive
Excellent! That does 90% of what i want, and i can figure out the rest on my own. Thanks.
Morrissey
Better yet, subtract ord('A').
DonaldRay
I don't see why that's better. That will give the wrong result, but if it's popular, so be it I guess.
recursive
Subtract ord('A') and then add back 1. The beauty of this is that it gets rid of the magic number 64, which is mysterious to those who have not memorized the ASCII table, but ord('A') is obvious what you are doing.
Paul McGuire
+2  A: 
import string

letter_to_numeral = dict(zip(string.uppercase, range(1, len(string.uppercase) + 1) ))

print letter_to_numeral
>>> {'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}

def score_string(s):
    return sum([letter_to_numeral[character] for character in s])


score_string('ABC')
>>> 6
awesomo
+3  A: 
def getvalue(mystring):
    letterdict = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ',range(1,27)))
    return sum(letterdict[c] for c in mystring)
bigjim
+8  A: 
base = ord('A') - 1
mystring = 'ABC'
print sum(ord(char) - base for char in mystring)
Tony Veijalainen
A: 

After you define the variables you can just return the answer or print the answer A = 1 B = 2 C = 3 total = A + B + C print (total) return total

luther07
+2  A: 

Enumerate can do the numbering for you:

import string
numerology_table = dict((ch,num+1) for (num,ch) in enumerate(string.ascii_letters[:26].upper()))
Paul McGuire
+1  A: 

If you are using Python3:

result = 0
mystring = 'ABC'
for char in mystring.encode('ascii'):
    result += char - 64

>>> result
6
Espen Rønnevik
A: 

Golfy answer certain to annoy your professor:

>>> s = 'ABC'
>>> sum(map(ord,s),-64*len(s))
6
Triptych
A: 

The most sensible answer is of course using ord as shown earlier. But for those who chose to construct a dictionary, I would rather just use the index in the string:

>>> import string
>>> mystring = 'ABC'
>>> sum(string.uppercase.index(c) + 1 for c in mystring)
6
Muhammad Alkarouri