-3

Write a function commonElements(t1, t2) that takes in 2 tuples as arguments and returns a sorted tuple containing elements that are found in both tuples.

Examples

>>> commonElements((1, 2, 3), (2, 5, 1))
(1, 2)
>>> commonElements((1, 2, 3, 'p', 'n'), (2, 5 ,1, 'p'))
(1, 2, 'p')
>>> commonElements((1, 3, 'p', 'n'), ('a', 2 , 5, 1, 'p'))
(1, 'p')

i want to compare between two tuples

 def commonElements(t1,t2):
     if t1 in t2:
        return t1 
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
Ramy George
  • 49
  • 1
  • 1
  • 4

2 Answers2

1

You would need to check if each element in t1 is in t2, your code just returns t1 when you find the first common element or None if there are no common elements:

def commonElements(t1,t2):
    temp = []  # store  common elements
    st2  = set(t2)
    for ele in t1: # loop over each element in t1
        if ele in st2: # if it is in t2 add it to or temp list, set lookups are O(1)
            temp.append(ele)
    return tuple(sorted(temp)) # sort temp and convert to a tuple

In [4]: commonElements((1, 2, 3), (2, 5, 1))
Out[4]: (1, 2)

In [5]: commonElements((1, 2, 3, 'p', 'n'), (2, 5 ,1, 'p'))
Out[5]: (1, 2, 'p')

In [6]: commonElements((1, 3, 'p', 'n'), ('a', 2 , 5, 1, 'p'))
Out[6]: (1, 'p')

You can also use sets or a generator expression:

def  commonElements(t1,t2):
     # find the intersection/common elements
    return tuple(sorted(set(t1).intersection(t2)))

def  commonElements(t1,t2):
    return tuple(sorted(ele for ele in t1 if ele in t2))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

You could use operator based intersection of sets .

def commonElements(one, two):
    return tuple(sorted(set(one) & set(two)))

commonElements((1,2,3), (2,3,4))
# (2, 3)
Alexander
  • 12,424
  • 5
  • 59
  • 76