user6882757
user6882757

Reputation:

How to find the max of key which has the max of key value product

Find the max of the key which is having the product max of key and value

I got the output, I am in search of best solution

a = [3,4,5,5,6,6,6,7,7]
c = set(a)
counts = {}
for i in a:
    if i in counts:
        counts[i] += 1
    else:
        counts[i] =1
#counts
t = [k*v for k,v in counts.items()]
max_index = t.index(max(t))
list(c)[max_index]

6

NO error, how to optimize the code. need list comprehension at the position

for[k*v for k,v in counts.items()]. Can i add map function to this?

Upvotes: 0

Views: 165

Answers (3)

Woobensky Pierre
Woobensky Pierre

Reputation: 66

this is how you can use a map to get the "t" list

def function(item):
    return item[0]*item[1]
t = list(map(function, counts.items()))

Upvotes: 1

Patrick Artner
Patrick Artner

Reputation: 51683

You can use collection.Counter or collections.defaultdict with int to do the counting for you (both are faster then your -valid- solution).

To get the maximum value use sorted()- see sorting overview with an appropriate key function:

from collections import Counter

a = [3,4,5,5,6,6,6,7,7]
c = Counter(a)

m = sorted(c.items(),key= lambda x: x[0]*x[1], reverse = True)
print(m)

Prints

[(6, 3), (7, 2), (5, 2), (4, 1), (3, 1)]

so m[0][0] would be your result of 6.

max(...) can also use the same key function, if you are only interested in the maximal value.


Defaultdict version (more lines then Counter):

from collections import defaultdict

a = [3,4,5,5,6,6,6,7,7]
c = defaultdict(int)
for num in a:
    c[num] += 1

Upvotes: 1

Barmar
Barmar

Reputation: 781751

Change your dictionary so the values are already multiplied by the keys. Then you can use one of the solutions in Getting key with maximum value in dictionary? to find the keys with the maximum value.

for i in a:
    if i in counts:
        counts[i] += i
    else:
        counts[i] = i

Upvotes: 0

Related Questions