victor victor - 2 months ago 22
Python Question

Looping through characters of a string with int values

I am attempting to solve a testcase from the USACO Training page: "your ride is here". I attempted to assign letters of the alphabet numerical values and multiply each character in a string for a product.

EX:

C O M E T Q

3 * 15 * 13 * 5 * 20 * 17 = 994500

Unfortunately, the product keeps getting messed up.

key = {'A':1,
'B':2,
'C':3,
'D':4,
'E':5,
'F':6,
'G':7,
'H':8,
'I':8,
'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}

infile = open("testdata.txt", "r")

message = infile.readline(2)
for character in message:
preSignal = key[character]
s = preSignal*key[character]
print(s)

Answer Source

You're overriding variable s every time and save squared key[character] to it (which is not right). You need to create a variable for keeping the result. Try this:

result = 1

for character in message:
    result *= key[character]

print(result)