Thinking Pythonically (was Re: gah! I hate the new string syntax)

Kirby Urner 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

   def sigma(f,stop,start=1):
      result = 0
      for i in range(start,stop+1):
	 result += f(i)
      return result

or

   def sigma(f,start,stop,start=1):
      return reduce(add,map(f,range(start,stop+1)))

or

   def sigma(f,stop,start=1):
      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:

  def gcd(n,m):
      """
      Euclid's Algorithm for GCD
      """
      while m:
         n,m = m,n%m
      return n

  def relprimes(n):
      """
      List coprimes < n
      """
      return [x for x in range(1,n) if gcd(n,x)==1]

So neat, so clean!  Pythonic math is kewl.

Kirby
	



More information about the Python-list mailing list