python - Converting raw input string to numbers (for each letter) then summing the numbers -


this question has answer here:

i want user enter word e.g. apple , convert each character in string corresponding letter (a = 1, b = 2, c = 3 etc.)

so far i've defined letters

a=1 b=2 c=3 d=4  e=5  f=6  g=7  etc... 

and have split string print out each letter using

word = str(raw_input("enter word: ").lower())  in range (len(word)):     print word[i] 

this prints characters individually, can't figure out how print these corresponding numbers, sum together.

in case, better use dictionary defines characters , there value. string library provides easier way this. using string.ascii_lowercase within dict comprehension can populate dictionary mapping such.

>>> import string >>> wordmap = {x:y x,y in zip(string.ascii_lowercase,range(1,27))} >>> wordmap {'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} 

now can map output. first take input

>>> word = str(raw_input("enter word: ").lower()) enter word: apple >>> values = [] 

now loop through input word , append values empty list. append values because need find sum of values.

>>> in word: ...     print "{}".format(wordmap[i]) ...     values.append(wordmap[i]) ...  1 16 16 12 5 

you can use sum function output sum total of values.

>>> sum(values) 50 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -