Thinking Pythonically (was Re: gah! I hate the new string syntax)
urner at alumni.princeton.edu
Sat Mar 3 20:05:12 CET 2001
Donn Cave <donn at oz.net> wrote:
>I used to use map, filter, reduce, but a couple of years ago
>I gave that up because I felt it would make my code harder
>for other people to read. An explicit loop is better.
> Donn Cave, donn at oz.net
I think it's possible to go overboard with the 'functional
programming' type operators (if we can call 'em that), but
I prefer to use them within reason vs. not use them at all
-- and I think the new list comprehension syntax makes the
code even more readable.
For example, when doing sigma (sum of terms), passing in
the function and lower/upper term indices, you could write:
from operator import add # used below
def f(x): return x*x # example function
result = 0
for i in range(start,stop+1):
result += f(i)
return reduce(add,[f(x) for x in range(start,stop+1)])
This last is my personal favorite. I don't find
it harder to read than the first.
And I _really_ like the combination of functions
below for listing out numbers < n that are relatively
prime to n:
Euclid's Algorithm for GCD
n,m = m,n%m
List coprimes < n
return [x for x in range(1,n) if gcd(n,x)==1]
So neat, so clean! Pythonic math is kewl.
More information about the Python-list