dedpo
dedpo

Reputation: 502

I am trying to find the set of lists in a tuple

for example,

(['2', '3', '5'], ['1', '3', '4', '5'])

the above should yield the numbers 3 and 5

(['1', '2', '4'], ['1', '2'])

this should give out 1 , 2

(['2', '3', '5'], ['1', '2', '4'], ['2', '3'])

this, should give out 2, because 2 is contained in all 3 lists in the tuple. If there is no set it should just return an empty list

for i,e in enumerate(tup):
while index < len(tup):
    print(tup[index], tup[index + 1])
    index = index + 1

For now i have this, i am not sure how to go through the tup(Tuple) and extract each list to find the set of each 2 lists and iterate and compare with the rest of lists in the tuple

Upvotes: 1

Views: 84

Answers (4)

timgeb
timgeb

Reputation: 78650

Be consistent in return types. Don't return an empty string when you have an empty set.

That being said, I'd find the numbers like this:

>>> lsts = (['2', '3', '5'], ['1', '3', '4', '5'])
>>> set(lsts[0]).intersection(*lsts[1:])
set(['3', '5'])
>>> 
>>> lsts = (['1', '2', '4'], ['1', '2'])
>>> set(lsts[0]).intersection(*lsts[1:])
set(['1', '2'])
>>> 
>>> lsts = (['2', '3', '5'], ['1', '2', '4'], ['2', '3'])
>>> set(lsts[0]).intersection(*lsts[1:])
set(['2'])

The function for that would be:

>>> def common(lsts):
...     return set() if not lsts else set(lsts[0]).intersection(*lsts[1:])

Upvotes: 2

Marcus M&#252;ller
Marcus M&#252;ller

Reputation: 36337

Simple as that: python has a set type, so just

sets = [set(l) for l in (['2', '3', '5'], ['1', '3', '4', '5']) ]
common_elements = reduce(lambda a,b: a & b, sets)

Upvotes: 1

Julien Spronck
Julien Spronck

Reputation: 15423

def intersect(lists):
    return list(set.intersection(*map(set, lists)))

Upvotes: 6

inspectorG4dget
inspectorG4dget

Reputation: 113915

In [8]: t = (['2', '3', '5'], ['1', '3', '4', '5'])

In [9]: functools.reduce(lambda a,b: set.intersection(set(a), set(b)), t)
Out[9]: {'3', '5'}

Upvotes: 3

Related Questions