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).
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).
You can use ord
to get the ascii code, then subtract 64.
def codevalue(char):
return ord(char) - ord('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
def getvalue(mystring):
letterdict = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ',range(1,27)))
return sum(letterdict[c] for c in mystring)
base = ord('A') - 1
mystring = 'ABC'
print sum(ord(char) - base for char in mystring)
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
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()))
If you are using Python3:
result = 0
mystring = 'ABC'
for char in mystring.encode('ascii'):
result += char - 64
>>> result
6
Golfy answer certain to annoy your professor:
>>> s = 'ABC'
>>> sum(map(ord,s),-64*len(s))
6
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