Sharpless512 Sharpless512 - 1 year ago 77
Python Question

frozenset at least x elements

I currently have this code, it checks if all elements in the array are the same. If this is the case, return true

def all_equal(lst):
>>> all_equal([1,1,1,1,1,1,1])
>>> all_equal([1,2,3,1])
return len(frozenset(lst)) == 1

But what I do want to check is if there are atleast 5 elements of the same.

So that


Will return True aswell. Since there are 5 times 1

Answer Source

Instead of using a set, use a bag or multiset type. A multiset counts how many times unique values occur.

In Python that's the collections.Counter() object:

from collections import Counter

def all_equal(lst):
    bag = Counter(lst)
    if any(v >= 5 for v in bag.itervalues()):
        # an element occurred at least 5 times
        # (use bag.values() if using Python 3)
        return True
    return False