Add operate with dictionary values

0

I want to make a small converter of letters to numbers (encrypted type). I have created a dictionary with each letter, assigning it a value. The intention is that the user write a word and the program translates the letters into numbers, add it and return the result.

The code I have is this:

codigo = {
    ' ': ' ',
    'A': '1', 
    'B': '2', 
    'C': '2', 
    'D': '4', 
    'E': '5', 
    'F': '8', 
    'G': '3', 
    'H': '8', 
    'I': '1', 
    'J': '1', 
    'K': '2', 
    'L': '3', 
    'M': '4', 
    'N': '5', 
    'O': '7', 
    'P': '8', 
    'Q': '1', 
    'R': '2', 
    'S': '3', 
    'T': '4', 
    'U': '6', 
    'V': '6', 
    'W': '6', 
    'X': '6', 
    'Y': '1', 
    'Z': '7', }


def convertir(frase):
    frase = frase.upper()
    encoded = ""
    for caracter in frase:
        encoded += codigo[caracter] + " " 
    return encoded

frase = input("Escribe una o varias palabras: ")
encoded = convertir(frase)

print(encoded)

And when I execute it, I can transform the words into numbers. For example, if I write hello, it returns:

  

Write one or more words: hello 8 7 3 1

But I do not know how to make the sum. I guess I have to turn it into integers and then add them, but I do not know how to do it.

What I want you to do is the corresponding sum 8 + 7 + 3 + 1 = 19 analyze the result (19) and add it again (1 + 9)

I appreciate any contribution.

    
asked by Aluq 10.09.2018 в 12:46
source

1 answer

0

You can iterate the characters of a String, in particular of your variable encoded , with a loop for

sum = 0
for c in encoded:
  sum += int(c)

or more concise by map (pairing from String to int) and reduce (to add)

result = reduce(
  lambda x,y: x+y, 
  map(lambda c: int(c), encoded)
)
    
answered by 10.09.2018 в 12:58