0

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?

  • 1
    Possible duplicate of [Getting key with maximum value in dictionary?](https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary) – m13op22 Jul 09 '19 at 17:17
  • 1
    @hs - Mous is looking for the max(Key*Value) in his dict ... – Patrick Artner Jul 09 '19 at 17:18
  • Are you certain your code is doing what you expect it to do? You are calculating the index of `max(t)` in `t` and then apply it to the set of unique items in `a` (which, AFAIK does not have a guaranteed order anyway). – PeterE Jul 09 '19 at 17:26

3 Answers3

1

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
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1

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()))
0

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
Barmar
  • 741,623
  • 53
  • 500
  • 612