Python 3.0 - is this true?
"Martin v. Löwis"
martin at v.loewis.de
Sun Nov 9 13:29:27 EST 2008
> def comp(x1, x2):
> try:
> if x1<x2:
> return -1
> else:
> return 1
> except TypeError:
> if str(x1)<str(x2):
> return -1
> else:
> return 1
>
Please correct me if I'm wrong, but I think this is not transitive. If
strings and ints are uncomparable, this will give you 20 < "5" and
"5" < 8, but not 20 < 8. As a result, quicksort will do nonsense
with that comparison function (i.e. it won't guarantee that things
are sorted in increasing order)
> Not sure how to transform it into a search key that is efficient and
> reliable.
Depending on what your notion of "sameness of lists" is, the following
might do:
def key(o):
return id(type(o)),o
This only requires that all objects of the same type in the list can
be sorted. If this is not guaranteed, then
def key(o)
try:
o<o
return id(type(o)),o
except TypeError:
return id(type(o)),id(o)
might do.
Regards,
Martin
More information about the Python-list
mailing list