user2672903
user2672903

Reputation: 1

Find elements which exists in the most of the lists

Input:

[[1,2,3],[1,5,7],[1,9,3],[4,3,8]]

Expected result:

[1,3]

(add element to result if it exists in over 50% of input lists).

I'm looking for elegant, pythonic solution :). Sorry for my bad english.

Upvotes: 0

Views: 52

Answers (1)

DSM
DSM

Reputation: 353009

How about:

>>> from collections import Counter
>>> s = [[1,2,3],[1,5,7],[1,9,3],[4,3,8]]
>>> count = Counter(term for subseq in s for term in set(subseq))
>>> [k for k,v in count.items() if v > len(s)//2]
[1, 3]

Counter is a handy tool which, well, counts things:

>>> Counter([1,2,3,3,2])
Counter({2: 2, 3: 2, 1: 1})

[.. oops, just noticed you're using Python 3, so we need .items()].

Upvotes: 4

Related Questions