How to give a scoring's based on an input word

Viewed 134

Shown below is the syntax used to give a score for a user based on the letters from a user input word,

letter_with_score = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,
                         'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,
                         'u':21,'v':22,'w':23,'x':24,'y':25,'z':26, ' ':0}
    

while True: 
    user = input("Enter a word: ").lower()
    print()
    
    user_word_split = []
    score = []


    for i in user:
        user_word_split.append(i)
    

    for k, v in letter_with_score.items(): 
        if k in user_word_split: 
            score.append(v)
        
    print()
    print(sum(score))
    print()

However, for an example if a user inputs a word such as "Hello", the user will get a score of 40. Where the actual score should be 52.

How can this be resolved to get the actual score.

4 Answers

Try this oneliner using map on user input with mapping function dict.get:

while True: 
    user = input("Enter a word: ").lower()
    score = sum(map(lambda l: letter_with_score.get(l, 0), user))
    print(score)

Output

Enter the word: hello
52

The problem is you're iterating the dictionary. Let's take a case hello h e l l o 8 5 12 12 15

When you check l twice and get 12 twice and try to append in the score list. But having 12 already in the score list it's overriding the first 12 that's why you're getting sum(score) is 40

while True:
    user = input("Enter a word: ").lower()
    score = []
    for i in user:
        if i in letter_with_score.keys():
            score.append(letter_with_score[i])
    print()
    print(sum(score))
    print()

Your letter_with_score is a dictionary, so you can get the score for each letter by indexing that dictionary with []. Thus you can construct a list of the scores for each letter in the input word (not just the unique letters) and sum over that list to get the total score:

letter_with_score = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,
                     'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,
                     'u':21,'v':22,'w':23,'x':24,'y':25,'z':26, ' ':0}
    
user = input("Enter a word: ").lower()

scores = [letter_with_score[letter] for letter in user]
print(sum(scores))

Note that you can iterate over a string directly, so there is no need to split the input word into letters first.

Instead of taking all the values from a to z in a dictionary , I have a better approach for you

You can simply use asci value of the character using ord()

try the following code it will be simple and easily understandable

T=input()
T=T.lower()
total=0
for i in range(len(T)):
    if T[i]==" ":
        total=total+0
    else:
        total=total+int(ord(T[i])-96)
print(total)
Related