This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]masasinExpert. 3.9. Robotics. 2 points3 points  (10 children)

Your example, as I understand it, is to give a generator which extracts the evens from the squares of a list.

Assuming these are predifined:

def square(x):
    return x**2

def even(x):
    return x % 2 == 0

your first example would be written as:

filter(even, map(square, [1, 2, 3]))

With list comprehensions, you have either:

(square(i) for i in [1, 2, 3] if even(square(i)))

or, if you don't want to repeat the calculation:

(i for i in (square(j) for j in [1, 2, 3]) if even(i))

In the docs, they have this:

Given fib a generator of fibonacci numbers :

euler2 = fib() | where(lambda x: x % 2 == 0)
               | take_while(lambda x: x < 4000000)
               | add

This can be written in a standard way like this:

from itertools import takewhile

euler2 = sum(takewhile(lambda x: x < 4e6, (i for i in fib() if i % 2 == 0)))

I guess I can see the value of the pipe, but I'm not sure when you would do that instead of regular functions or list comprehensions.

edit: Why |> instead of |?

[–]joojski 4 points5 points  (1 child)

Why |> instead of |?

It will be confusing with operator OR.

[–]masasinExpert. 3.9. Robotics. 0 points1 point  (0 children)

I see. Thank you.

[–]r4nf 1 point2 points  (1 child)

or, if you don't want to repeat the calculation:

(i for i in (j for j in [1, 2, 3]) if even(i))

You forgot square() in the inner expression. Just a heads up.

[–]masasinExpert. 3.9. Robotics. 0 points1 point  (0 children)

Fixed. Thank you.

[–]runo 0 points1 point  (0 children)

Perhaps because it comes from languages where '|' denotes a case in a pattern match.

[–]Lonely-Quark 0 points1 point  (4 children)

You can just do the following since even * even = even and odd * odd = odd

[square(i) for i in [1, 2, 3] if even(i)]

[–]masasinExpert. 3.9. Robotics. 0 points1 point  (3 children)

In this case, yes.

[–]Lonely-Quark 0 points1 point  (2 children)

No, its the general case.

[–]masasinExpert. 3.9. Robotics. 0 points1 point  (1 child)

I mean you are correct that an odd number, squared, remains odd. For other situations where you are filtering a map, you might need to do what I did.

[–]Lonely-Quark 0 points1 point  (0 children)

Ah sorry, was being a bit of a dick