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 no开发者_运维技巧t return True
. What is wrong?
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
First, your code could be replaced by:
def cmpT(t1, t2):
return t1 == t2
Second, I have no idea why it isn't working. It works fine for me too.
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)
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...
精彩评论