tree em
tree em

Reputation: 21721

Test whether tuples have the same content

I have to implement a function cmpT which should return the following results:

>>> cmpT((1, 2), (1, 2))
True
>>> cmpT((1, 2), (2, 1))
True
>>> cmpT((1, 2), (1, 2, 1))
False
>>> cmpT((1, 2), ())
False

My Code:

 def cmpT(t1, t2): 
    if t1 == t2:
        return True
    else:
        return False

It does not give the required output, cmpT((1, 2), (2, 1)) does not return True. What is wrong?

Upvotes: 3

Views: 27227

Answers (3)

amit
amit

Reputation: 178451

You should check for each element if it is in both lists and the same number of times. The best solution is just sorting.

def cmpT(t1, t2): 
    return sorted(t1) == sorted(t2)

Have a look: http://codepad.org/PH6LrAvU

Upvotes: 16

steabert
steabert

Reputation: 6878

Like in my comment:

def cmpT(t1, t2):
    return len(t1) == len(t2) and set(t1) == set(t2)

I don't know if it is faster than sorting for large tuples...

Upvotes: -3

ScienceFriction
ScienceFriction

Reputation: 1558

If you want to compare the content of two sets you have to convert the tuples to sets.

>>> a = set((1,2))
>>> b = set((2,1))
>>> a
set([1, 2])
>>> b
set([1, 2])
>>> a==b
True

that is:

def compT(t1, t2):
    return set(t1) == set(t2)

Upvotes: -4

Related Questions