1

Multipy character position by ord() value of that character

I'm trying to make a function in python that would take a word, find ASCII value of each character in a word, then multiply each of the value by the position of the character in that word and sum together. I came up with below however I don't know how to multiply each 'x' with the position number of each char.

mystring = 'AZC'
total = 0
for c in mystring:
    x = ord(c)
    total += x
print(total)

this code returns value 222 (65 for 'A' + 90 for 'Z' + 67 for 'C') but I need 65 * 1 + 90 * 2 + 66 * 3 = 443 It will probably have something to do with substring but I am lost

Submitted September 16th 2021 by Admin

Answers
0

Use enumerate() to know the index of the character

for index, c in enumerate(mystring): x = ord(c) pos = index + 1 total += (x * pos)

Admin | 1 month ago


0

Use enumerate() to get the positions. And you can use the sum() function to add them all together.

total = sum(pos * ord(c) for pos, c in enumerate(mystring, 1))

The second argument 1 makes it start the positions at 1 instead of 0.

Admin | 1 month ago


0

mystring = 'AZC'
total = 0
for i,c in enumerate(mystring): x = ord(c) total += (x*(i+1))
print(total)

enumerate returns a tuple having the position as well as the element over which you are iterating.

Admin | 1 month ago



Relevant Questions