views:

257

answers:

4

I've seen some elegant python snippets using list comprehension and map reduce. Can you share some of these code or a web site.

Thanks.

+3  A: 

There are some nice functional style snippets in here: http://www.amk.ca/python/writing/functional

Nadia Alramli
+2  A: 

Here is quick sort:

def qsort (list):
    if (len(list) > 1):
        list = qsort(filter (lambda x: x <= list[0], list[1:])) + [list[0]] + qsort(filter (lambda x: x > list[0],  list[1:]))
    return list

This one is a solution to a programming puzzle of finding a missing number among the integers from 1 to 100:

from random import randint
nos = range(1,101)
to_remove = randint(1,100)
nos.remove(to_remove)
print "Removed %d from list" % to_remove

found = 5050 - reduce (lambda x,y: x+y, nos)
print "You removed %d " % found
Richie
+3  A: 

Python is not lisp. Please don't try to make it look that way. It only reduces one of python's biggest strengths, which is its readability and understandability later on.

If you like functional programming, learn Haskell, ML, or F#. You will be amazed at what those languages offer (pure functions to start with).

Joe Koberg
I agree about ML - often overlooked
zebrabox
+3  A: 

Be careful when programming python in functional style. The only reason to ever do so is for readability. If the algorithm is more elegantly expressed functionally than imperatively, and it doesn't cause performance problems (it usually doesn't), then go right ahead.

However, python does not optimize tail recursion, and has a fixed recursion limit of 1000, so you generally can't do O(n) recursion, only O(log(n)).

Also, reduce() is removed in python 3, for good reason ( http://www.artima.com/weblogs/viewpost.jsp?thread=98196 ). Most non-trivial uses of reduce are more readable as a normal loop instead of a reduction, and sum() is already built in.

Christian Oudard