Billy Mann
Billy Mann

Reputation: 87

Function for averages of tuples in a dictionary

I have a string, dictionary in the form:

('the head', {'exploded': (3.5, 1.0), 'the': (5.0, 1.0), 
"puppy's": (9.0, 1.0), 'head': (6.0, 1.0)})

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):
    for word in d:
        (score, std) = d[word]
        d[word]=float(score),float(std)
        if word in string:
            word = string.lower()
            number = len(string)
            return sum([v[0] for v in d.values()]) / float(len(d))
        if len(string) == 0:
            return 0

When I run:

print score('the head', {'exploded': (3.5, 1.0), 'the': (5.0, 1.0), 
"puppy's": (9.0, 1.0), 'head': (6.0, 1.0)})

I should get 5.5 but instead I'm getting 5.875. Can't figure out what in my function is not allowing me to get the correct answer.

Upvotes: 0

Views: 138

Answers (1)

Martin Maillard
Martin Maillard

Reputation: 2811

def score(s, d):
    included = [d[word][0] for word in d if word in s]
    return sum(included) / float(len(included))

Upvotes: 1

Related Questions