0

I'm trying to make a function which prints the common elements from two tuples which are taken by arguments. Can you give me a track?

def common_elements(t1, t2):
    element = t1,t2
    for x in element:
        if x in t1 and x in t2:
            print tuple(x)
common_elements((1,2,3),(1,4,5,2))
0

3 Answers 3

1

Use a set:

tuple(set((1,2,3)).intersection((1,4,5,2)))

result:

(1, 2)
Sign up to request clarification or add additional context in comments.

Comments

0

I think your assignment of element is the issue. Element itself is a tuple, so you if statement is evaluating if a tuple is in t1, which it is not, rather than if the element itself is. Try as a way to get all the elements in the tuple:

element = []
element.extend(t1)
element.extend(t2)

Now, your if statement should work. Also your print statement is weird.

Comments

0

While using element = t1,t2 this statement you are making tuples of the tuple. Example:-

>>> x=(3,4)
>>> y=(7,3)
>>> z=x,y
>>> z
((3, 4), (7, 3))

while calling for x in element: means x value will be t1 or t2 not elements of t1 and t2.

If x=t1 then calling if statement x in t1 and x in t2 will check if t1 is a element of t1 and also if t1 is a element of t2 which can't be possible because both are tuple not tuples of tuple. So your if statement will not be called. So print will never be executed.
Same will happen for x=t2

You can use Counter from collections for getting intersection like this:

>>> from collections import Counter
>>> a = Counter((1, 2, 3, 4, 4, 5, 5))
>>> b = Counter((4, 4, 5, 6, 7, 8))
>>> tuple(a & b)
    (4,5)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.