Write a function commonElements(a1, a2) that takes in 2 tuples as arguments and returns a sorted tuple containing elements that are found in both tuples.
My task is :
>>> 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 tried to do it like this.
def commonElements(a1, a2):
return tuple(set(a1).intersection( set(a2) ))
Anyone know what my mistake is with the requirement?
I can not pass.
Set is not ordered. So the order of the result may be arbitrary.
I would come up with something like that:
Please, note, that this way of solving the problem would get the output elements ordered as in the tuple
a1. So, as mentioned in the comments, the more correct way to call it is ‘ordering’, not ‘sorting’.Also, it has a complexity of
O(n*m), wherenandmare the lengths of the listsa1anda2respectively.O(n*log(m))can be achieved in this case ifbisectmodule is used to access the elements of the second tuplea2(which should be sorted before the proceeding).If sorting in common way is required, I would stick with your code, a bit altered:
On the average it has a complexity of
O(min(m+n)*log(min(n+m)))(because of sorting), andO(n*m)in the worst case because of intersection.If the code needs to be implemented without using
set(for example for the purposes of study), here is the code:Complexity is
O(n*m).With using
bisectthe code would look this way:Complexity is
O(n*log(m)).