sorting a dictionary
Mel Wilson
mwilson at the-wire.com
Thu Feb 6 09:38:09 EST 2003
In article <OXp0a.139082$0v.3923956 at news1.tin.it>,
Alex Martelli <aleax at aleax.it> wrote:
>In my case, it's the inconsistency between 2j<'1' working while 2j<1
>doesn't -- if both raised (or neither raised, as in 1.5.2), I could
>see the sense of it. I'd prefer the 1.5.2 behavior (so the subtle
>distinguos I had to draw in this thread were not needed) but I could
>accept "no complex number can EVER be compared with ANYTHING" as
>having some use (and no practical downside wrt the alternative of
>"complex numbers can be compared with strings but not with numbers").
With our penchant for dynamic typing we want to be able
to do
some_list_of_things.sort()
and not just get a mess of exceptions.
>But the current neither-fish-nor-fowl situation is just silly.
I guess it helps people who *are* doing mathematical
computing and have said `if a <= rj:` unaware that one of
the operands is no longer real.
I guess if you simply want to put a bunch of things into
a convenient arbitrary order, and you know there are complex
numbers around, you're going to have to write a custom
compare function and use the dire RTTI.
I guess it's a bit of a wart.
Regards. Mel.
What would that look like? (Python 2.1.3 dies
comparing a complex against a string.)
def square_peg_vs_round_hole (a, b):
## print a, type(a), b, type(b)
cplx_type = type (1+1j)
numeric_types = (type (0), type (0L), type (0.0))
if type (a) is cplx_type:
if type (b) is cplx_type:
return cmp (abs(a), abs(b)) # my choice of tactics
elif type (b) in numeric_types:
return 1 # sort complex after reals
else:
return -1 # complex before non-numeric
elif type (b) is cplx_type:
if type (a) in numeric_types:
return -1 # sort reals before complex
else:
return 1 # non-numeric after complex
else:
return cmp (a, b)
# end square_peg_vs_round_hole
Feeling of impending doom here if there is some type
`some_type` where I sort reals before complex, and complex
before some_type and the standard cmp wants to put some_type
before reals. That could be trouble.
More information about the Python-list
mailing list