8

I'm new to programming and I find myself in some trouble. I have a list, and I want to know how many times an item shows up and then print the minimum value that shows up. So if I have A=[1e, 2b, 3u, 2b, 1e, 1e, 3u, 3u], I want to show something like "What you want is a 2", where 2 is the least amount of times something shows up, in this case 2b is the one that shows up the least amount of times. This is my code so far:

import collections

collections.Counter(A)
B = {key: value for (key, value) in A}
result = []
min_value = None
minimum = min(B, key=B.get)
print(minimum, B[minimum])

The output for this is 2b, but what I want the amount of times 2b shows up, since it is the one that shows up the least. I'm having some difficulty with this. To clarify, I want the minimum number in a counter result.

Any help would be appreciated, I'm sorry if my question is confusing English is not my first language and it's my first time doing something like this.

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
Malsum
  • 91
  • 1
  • 5

3 Answers3

4

Just use min on dict.items, where dict is a Counter object:

from collections import Counter
from operator import itemgetter

c = Counter(A)
min_key, min_count = min(c.items(), key=itemgetter(1))

Since dict.items returns a view of key-value pairs, you can unpack directly to min_key, min_count variables.

jpp
  • 159,742
  • 34
  • 281
  • 339
1

Your code is basically right... do you just have a typo in your first couple lines?

import collections

A = ['1e', '2b', '3u', '2b', '1e', '1e', '3u', '3u']
B = collections.Counter(A)
result = []
min_value = None
minimum = min(B, key=B.get)
print(minimum, B[minimum])  # prints "2b 2"
scnerd
  • 5,836
  • 2
  • 21
  • 36
1

Why not simply :

from collections import Counter

A = ['1e', '2b', '3u', '2b', '1e', '1e', '3u', '3u']

c = Counter(A)
print(c.most_common()[-1])  # Print ('2b', 2)

Here is the documentation for most_common()


Edit (see comment of @Back2Basics)

most_common() has to sort all the items by value which at best is N Log(N). If you use min() then you only have to go through one pass of the array, so it's N.

Astariul
  • 2,190
  • 4
  • 24
  • 41
  • 3
    most_common() has to sort all the items by value which at best is N Log(N). If you use min() then you only have to go through one pass of the array, so it's N. (typically we are talking about minuscule (time and memory) gains so it's not really that important, but every once in a while you need to know the difference.) – Back2Basics Jul 28 '21 at 22:13
  • @Back2Basics Thanks for your comment, I didn't know. I'll update the answer to include your comment – Astariul Jul 30 '21 at 00:35