Lambda Function and More

Reference Documents

Lambda, Filter, Reduce and Map

  • The lambda operator or lambda function is a way to create small anonymous functions.
  • These functions are throw-away functions, i.e. they are just needed where they have been created.
  • Lambda functions are mainly used in combination with the functions filter(), map() and reduce().

Basic Syntax of a Lambda Function


In [ ]:
lambda argument_list: expression 

# The argument list consists of a comma separated list of arguments and 
# the expression is an arithmetic expression using these arguments.

In [ ]:
f = lambda x, y : x + y
f(2,1)

Lambda as macro


In [ ]:
line1 = "A cat, a dog  "
line2 = "  a bird, a mountain"

# Use X as an alias for two methods.
x = lambda s: s.strip().upper()

# Call the lambda to shorten the program's source.
line1b = x(line1)
line2b = x(line2)

print(line1b)
print(line2b)

Map Function

map() is a function with two arguments:


In [ ]:
r = map(func, seq)

The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq. It returns a new list with the elements changed by func


In [ ]:
def fahrenheit(T):
    return ((float(9)/5)*T + 32)
def celsius(T):
    return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)

F = map(fahrenheit, temp)
print F
C = map(celsius, F)
print C

In [ ]:
# map() can be applied to more than one list. 
# The lists have to have the same length.
a = [1,2,3,4]
b = [17,12,11,10]
c = [-1,-4,5,9]
map(lambda x,y:x+y, a,b)

In [ ]:
map(lambda x,y,z:x+y+z, a,b,c)

In [ ]:
map(lambda x,y,z:x+y-z, a,b,c)

Problem 1


In [ ]:
words = 'The quick brown fox jumps over the lazy dog'.split()
print words
stuff = []
for w in words:
    stuff.append([w.upper(), w.lower(), len(w)])

for i in stuff:
    print i

Use list comprehension and lambda/map function to define stuff.


In [ ]:

Filter Function

The function filter(func, iterableType) offers an elegant way to filter out all the elements of any iterable type (list, tuple, string, etc.), for which the function func returns True.


In [ ]:
fib = [0,1,1,2,3,5,8,13,21,34,55]
result = filter(lambda x: x % 2, fib)
print result

result = filter(lambda x: x % 2 == 0, fib)
print result

Problem 2

Use the filter function to remove all the vowels from the sentence


In [21]:
sentence = "It's a myth that there are no words in English without vowels."
vowels = 'aeiou'

In [ ]:

Reduce Function

The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value.

Syntax


In [ ]:
def reduce( aFunction, aSequence, init= 0 ):
    r= init
    for s in aSequence:
        r= aFunction( r, s )
    return r

Examples


In [ ]:
A = reduce(lambda x,y: x+y, [47,11,42,13])
print A

# Determining the maximum of a list of numerical values by using reduce
f = lambda a,b: a if (a > b) else b
B = reduce(f, [47,11,42,102,13])
print B

# Calculating the sum of the numbers from 1 to n: 
n = 300
C = reduce(lambda x, y: x+y, range(1,n+1))
print C

In [ ]:
def x100y(x,y):
    return 100*x+y

reduce(x100y, [13])
reduce(x100y, [2, 5, 9])
reduce(x100y, [2, 5, 9], 7)

Problem 3

Use the reduce function to find the product of all the entries in the list [47,11,42,102,13]


In [ ]:
print reduce(lambda x,y: x*y, [47,11,42,102,13])

In [ ]:
# note that you can improve the speed of the calculation using built-in functions
# or better still: using the numpy module
from operator import mul
import numpy as np
a = range(1, 101)

print "reduce(lambda x, y: x * y, a)"
%timeit reduce(lambda x, y: x * y, a)   # (1)

print "reduce(mul, a)"
%timeit reduce(mul, a)                  # (2)

print "np.prod(a)"
a = np.array(a)
%timeit np.prod(a)                      # (3)

Exception Handling


In [ ]:
from IPython.display import YouTubeVideo
YouTubeVideo("hrR0WrQMhSs")
  • An exception is an error that happens during the execution of a program.
  • Exceptions are known to non-programmers as instances that do not conform to a general rule.
  • Exception handling is a construct to handle or deal with errors automatically.
  • The code, which harbours the risk of an exception, is embedded in a try block.

Simple example


In [ ]:
def enter_number0():
    n = int(raw_input("Please enter a number: "))

enter_number0()

In [ ]:
def enter_number1():
    while True:
        try:
           n = raw_input("Please enter an integer: ")
           n = int(n)
           break
        except ValueError:
            print "No valid integer! Please try again ..."
    print "Great, you successfully entered an integer!"

enter_number1()

Some Exception Errors

  • IOError: The file cannot be opened
  • ImportError: Python cannot find the module
  • ValueError: A built-in operation or function receives an argument that has the right type but an inappropriate value.
  • KeyboardInterrupt: The user hits the interrupt key (normally Control-C or Delete)
  • EOFError: One of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data.
  • OverflowError, ZeroDivisionError, FloatingPointError:

An exhaustive list of built-in exceptions can be found here: https://docs.python.org/2/library/exceptions.html

else...


In [ ]:
def inverse_number0():
    try:
        x = float(raw_input("Your number: "))
        inverse = 1.0 / x
    except ValueError:
        print "You should have given either an int or a float"
    except ZeroDivisionError:
        print "Infinity"
    else:
        print "OK"
        
inverse_number0()

In [ ]:
# import module sys to get the type of exception
import sys

def inverse_number1():
    while True:
        try:
            x = int(raw_input("Enter an integer: "))
            r = 1/x
            break
        except:
            print "Oops!",sys.exc_info()[0],"occured."
            print "Please try again."
            print
    print "The reciprocal of",x,"is",r
    
inverse_number1()

Clean-up Actions (try ... finally)


In [ ]:
def inverse_number2():
    try:
        x = float(raw_input("Your number: "))
        inverse = 1.0 / x
    finally:
        print "There may or may not have been an exception."
    print "The inverse: ", inverse
    
inverse_number2()

In [ ]:
def inverse_number3():
    try:
        x = float(raw_input("Your number: "))
        inverse = 1.0 / x
    except ValueError:
        print "You should have given either an int or a float"
    except ZeroDivisionError:
        print "Infinity"
    finally:
        print "There may or may not have been an exception."
    
inverse_number3()

Raising Exceptions


In [ ]:
def achilles_arrow(x):
    if abs(x - 1) < 1e-3:
        raise StopIteration
    x = 1 - (1-x)/2.
    return x

In [ ]:
x=0.0

while True:
    try:
        x = achilles_arrow(x)
    except StopIteration:
        break
        
print "x = ", x

In [ ]: