Python 3.0 - is this true?

Kay Schluehr kay.schluehr at gmx.net
Sun Nov 9 01:53:14 EST 2008


On 9 Nov., 07:06, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Sat, 08 Nov 2008 20:36:59 -0800, Kay Schluehr wrote:
> > On 9 Nov., 05:04, Terry Reedy <tjre... at udel.edu> wrote:
>
> >> Have you written any Python code where you really wanted the old,
> >> unpredictable behavior?
>
> > Sure:
>
> > if len(L1) == len(L2):
> >     return sorted(L1) == sorted(L2)  # check whether two lists contain
> > the same elements
> > else:
> >     return False
>
> > It doesn't really matter here what the result of the sorts actually is
> > as long as the algorithm leads to the same result for all permutations
> > on L1 ( and L2 ).
>
> How often do you care about equality ignoring order for lists containing
> arbitrary, heterogeneous types?

A few times. Why do you care, Steven?

> In any case, the above doesn't work now, since either L1 or L2 might
> contain complex numbers.
> The sorted() trick only works because you're
> making an assumption about the kinds of things in the lists. If you want
> to be completely general, the above solution isn't guaranteed to work.

You are right. I never used complex numbers in Python so problems were
not visible. Otherwise the following comp function in Python 2.X does
the job:

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

Not sure how to transform it into a search key that is efficient and
reliable.

[...]

> Here is a way to
> solve the problem assuming only that the items support equality:
>
> def unordered_equals2(L1, L2):
>     if len(L1) != len(L2):
>         return False
>     for item in L1:
>         if L1.count(item) != L2.count(item):
>             return False
>     return True

Which is O(n**2) as you might have noted.





More information about the Python-list mailing list