9

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.

1
  • 10
    Good question, but community wiki! Commented Jan 19, 2010 at 12:26

4 Answers 4

7

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).

Sign up to request clarification or add additional context in comments.

1 Comment

I agree about ML - often overlooked
5

There are some nice functional style snippets in here: Functional Programming HOWTO

Comments

3

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.

1 Comment

reduce is still in functools though.
2

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.