How to sort a list? NOT a newbie question.
Alex Martelli
aleax at aleax.it
Wed Sep 19 06:20:49 EDT 2001
"Michael James Barber" <mjbarber at ascc.artsci.wustl.edu> wrote in message
news:9o9mga$fmp at ascc.artsci.wustl.edu...
I had claimed Michael needed to test set-equality, but he notices:
...
> Actually, this won't work in general. Consider having repeated roots of,
> say, [1j,1j,-1j].
True! So, you need to test MULTI-SET equality -- i.e.
to associate a *count* (number of occurrences) to each
member in the (multi-)set.
> It needs to be slightly modified to something like:
>
> def all_coefficient_are_real(roots):
> rootset = {}
> for root in roots:
> rootset[root] = rootset.get(root,0)+1
> for root in roots:
> if rootset[root] != rootset.get(root.conjugate(),0):
> return 0
> return 1
>
> Untested, but it looks right.
Yep. Or, one could be slightly trickier, e.g.:
def all_coefficient_are_real(roots):
rootset = {}
for root in roots:
conj = root.conjugate()
rootset[root] = rootset.get(root,0)+1
rootset[conj] = rootset.get(conj,0)-1
return not filter(None, rootset.values())
(also "untested, but":-) -- however, the simpler
approach is no doubt preferable!
Alex
More information about the Python-list
mailing list