Functional programming

Paradigm that means you're not carrying around a state, or mutating data. This is best demonstrated with examples.

This is an "imperative" style, not a "functional" style

In [ ]:
a = 5

def f():
    global a
    a *= a
    
f()
f()
f()
print(a)

This is a functional style

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

x = f(5)
x = f(x)
x = f(x)

print(x)

Even more functional!

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

x = f(f(f(5)))

print(x)

The place where functional programming matters most is with collections, like lists. Suppose that we want to apply a function to lists. First, let's define a function:

In [ ]:
def f(x):
    return < ADD SOME CODE HERE >

print('f(5) is %s' % str(f(5)))
In [ ]:
l = range(10)
for i in range(len(l)):
    l[i] = f(l[i])
    
print(l)

Functional programming means not changing data. Instead, make copies and apply functions to them.

In [ ]:
l = range(10)

squared = [f(x) for x in l]
squared2 = map(f, l)

print(l)
print(squared)
print(squared2)

lambda syntax

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

print(square(5))

square = lambda x: x ** 2

print(square(5))

Lambda syntax is great for defining functions on-the-fly.

In [ ]:
l = range(10)
squared = map(lambda x: x ** 2, l)

print(squared)

Write your function above in lambda syntax

In [ ]:
l = range(10)
l2 = map(< FILL IN LAMBDA HERE > , l)

print(l2)

filter is another functional operator

In [ ]:
evens = filter(lambda x: x % 2 == 0, l)

print(evens)

Write our own filter with a lambda function

In [ ]:
l2 = filter(< FILL IN LAMBDA HERE >, l)

print(l2)

Useful packages: numpy, matplotlib

These are some of the most widely used modules for basic data science in Python.

numpy: numerical computing library, good for manipulating vectors and matrices

matplotlib: for all your plotting needs

In [ ]:
import numpy as np
import matplotlib.pyplot as plt
import seaborn # makes matplotlib defaults better

%matplotlib inline

Create numpy arrays with np.array

In [ ]:
arr1 = np.array([1,2,3,4])
arr2 = np.array([7,5,3,1])

Arithmetic works on numpy arrays

In [ ]:
arr1 + 5
In [ ]:
arr2 * 2
In [ ]:
arr1 + arr2

The below statement doesn't work, though.

In [ ]:
arr3 = np.array([10, 10])
arr1 * arr3

Plotting with matplotlib

In [ ]:
x = range(-100,100)
y = np.array(x) ** 3
plt.plot(x, y)
plt.show()
In [ ]:
arr = np.random.normal(size=100000)
plt.hist(arr, bins=100)
plt.show()
In [ ]:
x = np.random.normal(size=10000)
y = 2 * x + np.random.normal(size=10000) * 2
plt.scatter(x, y, alpha=0.5)
plt.show()
In [ ]:
x = np.random.normal(size=10000)
y = 2 * x + np.random.normal(size=10000) * 2
plt.scatter(x, y, alpha=0.5, label='My Points', c='cyan')
plt.plot([-4, 4], [-8, 8], c='k', label='Trend')
plt.xlabel("X")
plt.ylabel("Y")
plt.legend(loc=2)
plt.show()
In [ ]: