简体   繁体   中英

finding the maxaverage from given list of tuples

Write a Python function maxaverage(l) that takes a list of pairs of the form (name,score) as argument, where name is a string and score is an integer. Each pair is to be interpreted as the score of the named player. For instance, an input of the form [('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)] represents two scores of 73 and 7 for Kohli, two scores of 33 and 90 for Ashwin and one score of 122 for Pujara. Your function should compute the players who have the highest average score (average = total across all scores for that player divided by number of entries) and return the list of names of these players as a list, sorted in alphabetical order. If there is a single player, the list will contain a single name.

For instance, maxaverage([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)]) should return ['Pujara'] because the average score of Kolhi is 40 (80 divided by 2), of Ashwin is 61.5 (123 divided by 2) and of Pujara is 122 (122 divided by 1), of which 122 is the highest.

In the same way the solution should be ['Kohli', 'Ashwin'] if l = ([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara'‌​,22),('Ashwin',47)]) but I'm getting only kohli

from collections import defaultdict

def maxaverage(l):
    dl = []
    data_dict = defaultdict(list)
    for k, v in l:
        data_dict[k].append(v)
    data_dict = dict(data_dict)

    for k, v in data_dict.items():
        data_dict[k] = sum(v) / len(v)

    list(zip(data_dict.keys(), data_dict.values()))
    max(data_dict.values())
    x = (max(data_dict, key=data_dict.get))
    dl.append(x)
    return dl

Try these codes:

l = [('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 22), ('Ashwin', 47)]


def max_average(l):
    from operator import itemgetter
    from itertools import groupby
    lst_of_pairs = list()

    for key, group in groupby(sorted(l, key=itemgetter(0)), key=itemgetter(0)):
        scores = list(x[1] for x in group)
        avg = sum(scores) / len(scores)
        lst_of_pairs.append((key, avg))

        lst_of_pairs.sort(key=itemgetter(1), reverse=True)
    max_avg = lst_of_pairs[0][1]
    return list(e[0] for e in filter(lambda x: x[1] == max_avg, lst_of_pairs))


print(max_average(l))

And for the case in 'l', you can get ['Ashwin', 'Kohli'] as expected. Remeber that the groupby will only work on a sorted lists.

Just add a list comprehension at the end of the method to get the keys of dict based on max average ie

from collections import defaultdict

def maxaverage(l):
    data_dict = defaultdict(list)

    for k, v in l:
        data_dict[k].append(v)

    data_dict = dict(data_dict)

    for k, v in data_dict.items():
        data_dict[k] = sum(v) / len(v)

    dl = [i for i,j in data_dict.items() if j == max(data_dict.values())]
    return dl 

Output:

maxaverage([('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 22), ('Ashwin', 47)])
#['Ashwin', 'Kohli']

maxaverage(([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)]) 
#['Pujara']

Here is a corrected version of your code that ensures that the final result is sorted alphabetically. It also has some efficiency improvements:

from collections import defaultdict

def maxaverage(l):
    data_dict = defaultdict(list)
    for k, v in l:
        data_dict[k].append(v)

    data_dict = {k: sum(v)/len(v) for k,v in data_dict.items()}

    max_avg = max(data_dict.values())
    return sorted([k for k in data_dict if data_dict[k] == max_avg])


>>> maxaverage(([('Kohli',73),('Ashwin',33),('Kohli',7),('Pujara',122),('Ashwin',90)]))
['Pujara']

>>> maxaverage([('Kohli', 73), ('Ashwin', 33), ('Kohli', 7), ('Pujara', 22), ('Ashwin', 47)])
['Ashwin', 'Kohli']

Note that the solution in the 2nd test case should be ['Ashwin', 'Kohli'] , not ['Kohli', 'Ashwin'] (as stated in your question) because the final list should be sorted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM