How to determine if any value occurs more than twice in a list?

Multi tool use
How to determine if any value occurs more than twice in a list?
I have a list and would like to determine if any value occurs more than twice.
I've tried using collections and counter but I cannot get those to evaluate to a single True or False value.
myArray=[1,1,1,1,1,1,1,1,2]
I would like it to return: True
if any value occurs more than twice.
True
Any help is appreciated and it would really help if the solution was fast. I'm checking hundreds of thousands of lists. I'm new to programming and this is my first post.
2 Answers
2
You could always construct a histogram of the values and see if any entry is greater than two. It could look something like this:
def is_more_than_twice(l):
hist = {}
for el in l:
if el in hist:
hist[el] += 1
else:
hist[el] = 1
if hist[el] > 2:
return True
return False
You don't need to iterate until the end of the list, just until you've met the condition of seeing an element el
appearing more than twice.
el
You can use collections.Counter for this:
from collections import Counter
print any(count > 2 for count in Counter(myArray).values()) # True
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Where is your attempt? I see no code?
– antfuentes87
7 mins ago