Home > Enterprise >  Summation with values in a dictionary (Python)
Summation with values in a dictionary (Python)

Time:06-06

I am struggling with using summation in Python.

I obtain input, which is then autocorrected and all punctuation is removed:

text=input("Enter your text here: )

Then, I have a dictionary:

bread = {"bread": 7, "sourdough crusts": 10}

I determined if any key from bread existed in text with the code:

result = re.findall('|'.join(bread), text)

I want to find the sum of all the values, should the corresponding key exist in text. At the moment, my code looks like this:

for sentence, rating in bread.items():
     ssum = 0
     for i in range(len(result)):
           ssum = ssum   rating
print("Sum: "   str(ssum))

However, this produces incredibly random results. For example, if

text = bread sourdough crusts

It says that

ssum = 20

(even though it should equal 17).

What is going on here, and how do I fix it?

CodePudding user response:

By adding print(ssum) after the add you might get a good idea what is going on and why the result is "random".

7
14
10
20
Sum: 20

Each sentence rating is added len(result) times, but you are assigning ssum = 0 on each loop iteration, so you return only the last one. Instead, you want to simply check if the sentence is found in result and assign ssum outside the loop

import re

text = "bread sourdough crusts"
bread = {"bread": 7, "sourdough crusts": 10}
result = re.findall('|'.join(bread), text)
ssum = 0
for sentence, rating in bread.items():
    if sentence in result:
        ssum = ssum   rating
print("Sum: "   str(ssum))

CodePudding user response:

The algorithm you wrote is incorrect. You can use this code

import re

text=input("Enter your text here: ") # "bread sourdough crusts"
bread = {"bread": 7, "sourdough crusts": 10}
result = re.findall('|'.join(bread), text) # ['bread', 'sourdough crusts']

ssum = 0
for i in result:
    ssum  = bread[i]

print(ssum) # 17

  • Related