Monday, December 21, 2009

5 Handy python functions (lambdas)

Here's a list of 5 handy python lambda's you may need when solving a quick maths problem

1) The sum of all integers from 1 to n
triangle = lambda n: n*(n+1)/2

2) Factorial
factorial = lambda n: 1 if n<2 else n*factorial(n-1)
3) Get odd numbers
odds = lambda n: [k for k in range(1,n,2)]
4) Test whether a number is prime

is_prime = lambda n: False if n<2 else (0 not in [n%k for k in range(2,int(n**.5)+1)])
A number is prime when it has no factor other than 1 and itself. To determine whether the number is a prime, we need to check that it doesn't leave a reminder of 0 when divided by each number in the range of [2..square root of the number].

5) Primes sieve
This function returns the list of primes in the range [2..N]. It's the most cryptic of all but it makes use of the previous function to add a number to the generated list.
sieve = lambda n: [k for k in range(2,n+1) if (0 not in [k%i for i in range(2,int(k**.5)+1)])]
It could also be written as:

is_prime = lambda n: False if n<2 else (0 not in [n%k for k in range(2,int(n**.5)+1)])
sieve = lambda n: [k for k in range(2,n+1) if is_prime(k)]

2 comments:

  1. Why not "triangle = lambda n: n*(n+1)/2"?

    That way you don't have to do that clumsy floating point division and int conversion?

    ReplyDelete
  2. I agree with you on that. I've just updated it. I'm also busy writing a sequel to this entry.

    ReplyDelete