Finding the insertion point in a list
John Machin
sjmachin at lexicon.net
Sat Mar 17 06:29:39 EDT 2007
On Mar 17, 5:42 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Steven D'Aprano <s... at REMOVE.THIS.cybersource.com.au> writes:
> > or even
>
> > len(filter(lambda t, y=y: y>t, x))
>
> How about
>
> min(i for i,t in enumerate(x) if t >= y)
>
> or
>
> max(i for i,t in enumerate(x) if t <= y)
>
> Those are actually pretty direct.
I'd hate to see "indirect". Worse, the min-using gizmoid crashes when
y > x[-1] -- all your ifs are belong to False.
>>> x
[0, 100, 200, 1000]
>>> tests = [0, 1, 100, 150, 1000, 2000]
>>> [(y, max(i for i,t in enumerate(x) if t <= y)) for y in tests]
[(0, 0), (1, 0), (100, 1), (150, 1), (1000, 3), (2000, 3)]
Looks OK, iff one is happy with the OP's strange usage of "insert
point".
>>> xc = x[:]
>>> xc.insert(1, 150)
>>> xc
[0, 150, 100, 200, 1000]
Whoops.
Try this for size:
>>> [(y, sum(t <= y for t in x)) for y in tests]
[(0, 1), (1, 1), (100, 2), (150, 2), (1000, 4), (2000, 4)]
Cheers,
John
More information about the Python-list
mailing list