While we're talking about annoyances
Arnaud Delobelle
arnodel at googlemail.com
Sun Apr 29 10:30:50 EDT 2007
On Apr 29, 11:46 am, Michael Hoffman <cam.ac... at mh391.invalid> wrote:
> GHUM wrote:
> > Steven,
>
> >> def index(sequence):
> >> decorated = zip(sequence, xrange(len(sequence)))
> >> decorated.sort()
> >> return [idx for (value, idx) in decorated]
>
> > would'nt that be equivalent code?
>
> > def index(sequence):
> > return [c for _,c in sorted((b,a) for a, b in
> > enumerate(sequence))]
>
> Or even these:
>
> def index(sequence):
> return sorted(range(len(sequence)), key=sequence.__getitem__)
>
> def rank(sequence):
> return sorted(range(len(sequence)),
> key=index(sequence).__getitem__)
Better still:
def rank(sequence):
return index(index(sequence))
:)
But really these two versions of rank are slower than the original one
(as sorting a list is O(nlogn) whereas filling a table with
precomputed values is O(n) ).
Anyway I would like to contribute my own index function:
def index(seq):
return sum(sorted(map(list,enumerate(seq)), key=list.pop), [])
It's short and has the advantage of being self-documenting, which will
save Steven a lot of annoying typing I hope ;) Who said Python
couldn't rival with perl?
--
Arnaud
More information about the Python-list
mailing list