Sharpless512 - 1 year ago 68

Python Question

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])

True

>>> all_equal([1,2,3,1])

False

"""

return len(frozenset(lst)) == 1

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

So that

`[1,1,1,1,1,2,2]`

Will return True aswell. Since there are 5 times 1

Answer

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
```

Source (Stackoverflow)