a = 5
def f():
global a
a *= a
f()
f()
f()
print(a)
def f(x):
return x * x
x = f(5)
x = f(x)
x = f(x)
print(x)
def f(x):
return x * x
x = f(f(f(5)))
print(x)
list
s. Suppose that we want to apply a function to lists. First, let's define a function:¶def f(x):
return < ADD SOME CODE HERE >
print('f(5) is %s' % str(f(5)))
l = range(10)
for i in range(len(l)):
l[i] = f(l[i])
print(l)
l = range(10)
squared = [f(x) for x in l]
squared2 = map(f, l)
print(l)
print(squared)
print(squared2)
lambda
syntax¶def square(x):
return x ** 2
print(square(5))
square = lambda x: x ** 2
print(square(5))
l = range(10)
squared = map(lambda x: x ** 2, l)
print(squared)
l = range(10)
l2 = map(< FILL IN LAMBDA HERE > , l)
print(l2)
filter
is another functional operator¶evens = filter(lambda x: x % 2 == 0, l)
print(evens)
l2 = filter(< FILL IN LAMBDA HERE >, l)
print(l2)
import numpy as np
import matplotlib.pyplot as plt
import seaborn # makes matplotlib defaults better
%matplotlib inline
np.array
¶arr1 = np.array([1,2,3,4])
arr2 = np.array([7,5,3,1])
numpy
arrays¶arr1 + 5
arr2 * 2
arr1 + arr2
arr3 = np.array([10, 10])
arr1 * arr3
x = range(-100,100)
y = np.array(x) ** 3
plt.plot(x, y)
plt.show()
arr = np.random.normal(size=100000)
plt.hist(arr, bins=100)
plt.show()
x = np.random.normal(size=10000)
y = 2 * x + np.random.normal(size=10000) * 2
plt.scatter(x, y, alpha=0.5)
plt.show()
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()