Python Overview

Objectives

  • Review python
  • Introduction to functional concepts
  • Data analysis and visualization workflow

Scientific Hello World


In [ ]:
import math
r = float("4.2")
s = math.sin(r)
print('hello world! The sin({0}) = {1:0.2f}'.format(r,s))

There is a lot happening here!

Functional Python

Python acquired lambda, reduce, filter and map, courtesy of a Lisp hacker who missed them and submitted working patches. -Guido van Rossum

The map abstraction

How do we apply a function on a list of numbers?

Function: $x**2$

List: [1,2,3,4]


In [ ]:
def square(x):
    return x*x

numbers = [1,2,3,4]

In [ ]:
def map_squares(nums):
    res = []
    for x in nums:
        res.append( square(x) )
    return res

map_squares(numbers)

or...


In [ ]:
results = map(square, numbers)
results

Anonymous functions: lambda


In [ ]:
lambda_square = lambda x: x*x
map(lambda_square, range(10))

In [ ]:
map(lambda x: x*x, range(10))

In [ ]:
res = map(lambda x: x*x, range(10))
print(res)

reduce

Apply a function with two arguments cumulatively to the container.


In [ ]:
def add_num(x1, x2):
    return x1+x2

print(reduce(add_num, res))

In [ ]:
import numpy as np
np.sum(res)

In [ ]:
print(reduce(lambda x,y: x+y, res))

filter

Constructs a new list for items where the applied function is True.


In [ ]:
def less_than(x):
    return x>10

filter(less_than, res)

In [ ]:
filter(lambda x: x>10, res)