I have a string, dictionary in the form:
('(Laughter flower)',
{'laughter': (8.5, 0.9313),
'flower': (7.88, 1.1718),
'the': (4.98, 0.9145),
'puppy': (7.58, 1.4581),
'died': (1.56, 1.198),
'laugh': (9.5, 0.1),
'flow': (2.3, 0.51)
}
)
Each parentheses is a tuple which corresponds to (score, standard deviation). I’m taking the average of just the first integer in each tuple. I’ve tried this:
def score(string, d):
if len(string) == 0:
return 0
string = string.lower()
included = [d[word][0]for word in d if word in string]
return sum(included) / len(included)
When I run:
print score ('(Laughter flower)', {'laughter': (8.5, 0.9313), 'flower':
(7.88, 1.1718), 'the':(4.98, 0.9145), 'puppy':(7.58, 1.4581),
'died':(1.56, 1.198),'laugh': (9.5, 0.1),'flow': (2.3, 0.51)})
I should get the average of only 'laughter' and 'flower': 8.5 + 7.88 / 2 but this running function also includes 'laugh' and 'flow' : 8.5 + 7.88 + 9.5 + 2.3 /4.
@Ignaco is right about why you’re including “flow” and “laugh”…
You could write the code as the following though:
so you generalise the function to just average the first element of relevant keys:
And you have to pre-process some string somehow, so that it’s a sequence of valid keys: