1

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

dedpo
  • 482
  • 11
  • 30

4 Answers4

6
def intersect(lists):
    return list(set.intersection(*map(set, lists)))
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
3
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'}
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
2

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:])
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

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)
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94