Home > database >  Looping throug a string and getting adding up each letters value to a total
Looping throug a string and getting adding up each letters value to a total

Time:03-28

in the variable line i have a sequence of letters. I have to loop over these letters and add up each of the letters value (the value is in the dictionary thisdict) to a total also i have to use a while loop and a for loop

In the screenshot i have tried this but it doesn't have any succes because i get the error code KeyError: ' '

line = "MAGQAFRKFLPLDRVLVERSAAETVKGGIMLPEKSAGKVLQATVVAVGSGSKGKGGEIAPVSVKVGDKVLLPEYGGTKVVLDDKDYFLFRDGILGKYD "
thisdict = {
    "A": 54,
    "C": 15,
    "D": 1964,
    "O": 15
}
mass = 0
while line != " ":
    for element in line:
        if element in thisdict: [element]
    mass  = thisdict[element]
print(mass)

CodePudding user response:

1- you have a problem with the indentation, this is the first thing:

line = "MAGQAFRKFLPLDRVLVERSAAETVKGGIMLPEKSAGKVLQATVVAVGSGSKGKGGEIAPVSVKVGDKVLLPEYGGTKVVLDDKDYFLFRDGILGKYD "
thisdict = {
    "A": 54,
    "C": 15,
    "D": 1964,
    "O": 15
}
mass = 0
while line != " ":
    for element in line:
        if element in thisdict:
            mass  = thisdict[element]
print(mass)

2- you are not removing the element when you finish incrementing the value of the element, in consequence the while loop doesn't stop.

CodePudding user response:

In order to count the number of points, you simply have to go through all the characters of the string (which you are already doing with your for loop), and add the value to mass if the character is referenced in the dict.

  • Your while loop is irrelevant here. As long as line is different from " ", you execute the code but the value of line never changes, so you are stuck in an infinite loop.
  • It is necessary to add the value to mass only if the key exists, you must thus move mass = ... in the if condition.

line = "MAGQAFRKFLPLDRVLVERSAAETVKGGIMLPEKSAGKVLQATVVAVGSGSKGKGGEIAPVSVKVGDKVLLPEYGGTKVVLDDKDYFLFRDGILGKYD "
thisdict = {
    "A": 54,
    "C": 15,
    "D": 1964,
    "O": 15
}
mass = 0
for element in line:
    if element in thisdict:
        mass  = thisdict[element]
print(mass)  # 14180

Note: you can also use .count() to count the number of times a substring appears in the string.

mass = 0
for char in thisdict:
    mass  = line.count(char) * thisdict[char]
print(mass)  # 14180
  • Related