Nils Bruin wrote:
> On Dec 12, 4:24 pm, Jason Grout <jason-s...@creativetrax.com> wrote:
>> [f(x) for x in [1..10] if f(x)>0]
> 
> This is actually bad style. It means that f gets evaluated twice for
> all the values that end up in the list.

Good point.

> The magma language solves this with modified semantics for the "where"
> clause. One would write:
> 
> [ v : x in [1..10] | v gt 0 where v:=f(x)]
> 
> The point being that for every iteration of x, the where clause
> supplies a variable local to the condition which survives into the
> value computing part.
> Does python have a similar construct? I guess a nested construction
> with iterators might come close:
> 
> [v for v in ( f(x) for x in [1..10] ) if v > 0]
> 
> but I don't know what the overhead is in that construction.
> 

There's apparently a lot more overhead than I would have imagined:

sage: %timeit [v for v in (x for x in range(10) ) if v > 0]
100000 loops, best of 3: 5.4 盜 per loop
sage: %timeit [v for v in range(10) if v>0]
100000 loops, best of 3: 2.98 盜 per loop

Interestingly, the builtin filter function isn't much faster than the 
slow version above:

sage: %timeit filter(lambda x: x>0, range(10))
100000 loops, best of 3: 5.3 盜 per loop

and a hand-coded filter is about the same speed:


   1 def fltr(lst):
   2     result=[]
   3     for x in lst:
   4         v = x
   5         if v>0:
   6             result.append(v)
   7     return result

sage: %timeit fltr(range(10))
100000 loops, best of 3: 5.18 盜 per loop

Thanks,

Jason



-- 
Jason Grout

-- 
To post to this group, send an email to sage-devel@googlegroups.com
To unsubscribe from this group, send an email to 
sage-devel+unsubscr...@googlegroups.com
For more options, visit this group at http://groups.google.com/group/sage-devel
URL: http://www.sagemath.org

Reply via email to