In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
In [2]:
max_iter = 100
h, w = 400, 400
img = np.zeros((h, w)).astype('int')
for i, real in enumerate(np.linspace(-1.5, 0.5, w)):
for j, imag in enumerate(np.linspace(-1, 1, h)):
c = complex(real, imag)
z = 0 + 0j
for k in range(max_iter):
z = z*z + c
if abs(z) > 2:
break
img[j, i] = k
plt.grid(False)
plt.imshow(img, cmap=plt.cm.jet)
pass
In [3]:
def mandel(c, z=0, max_iter=100):
for k in range(max_iter):
z = z*z + c
if abs(z) > 2:
return k
return k
In [4]:
def mandelbrot(w, h, xl=-1.5, xu=0.5, yl=-1, yu=1):
img = np.zeros((h, w)).astype('int')
for i, real in enumerate(np.linspace(xl, xu, w)):
for j, imag in enumerate(np.linspace(yl, yu, h)):
c = complex(real, imag)
img[j, i] = mandel(c)
return img
In [5]:
img = mandelbrot(w=400, h=400)
plt.grid(False)
plt.imshow(img, cmap=plt.cm.jet)
pass
In [6]:
img = mandelbrot(w=400, h=400, xl=-0.75, xu=-0.73, yl=0.1, yu=0.12)
plt.grid(False)
plt.imshow(img, cmap=plt.cm.jet)
pass
In [7]:
def square(x):
return x*x
In [8]:
square(3)
Out[8]:
In [9]:
square2 = lambda x: x*x
In [10]:
square2(3)
Out[10]:
In [11]:
# functions can be treated the same way as (say) an integer
In [12]:
def grad(x, f, h=0.01):
return (f(x+h) - f(x-h))/(2*h)
In [13]:
def f(x):
return 3*x**2 + 5*x + 3
In [14]:
grad(0, f)
Out[14]:
In [15]:
import time
def timer(f):
def g(*args, **kwargs):
start = time.time()
result = f(*args, **kwargs)
elapsed = time.time() - start
return result, elapsed
return g
In [16]:
def f(n=1000000):
s = sum([x*x for x in range(n)])
return s
timed_func = timer(f)
In [17]:
timed_func()
Out[17]:
In [18]:
@timer
def g(n=1000000):
s = sum([x*x for x in range(n)])
return s
In [19]:
g()
Out[19]:
In [20]:
map(lambda x: x*x, [1,2,3,4])
Out[20]:
In [21]:
list(map(lambda x: x*x, [1,2,3,4]))
Out[21]:
In [22]:
list(filter(lambda x: x%2==0, [1,2,3,4]))
Out[22]:
In [23]:
from functools import reduce
In [24]:
reduce(lambda x, y: x*y, [1,2,3,4], 10)
Out[24]:
In [25]:
[x*x for x in [1,2,3,4]]
Out[25]:
In [26]:
[x for x in [1,2,3,4] if x%2 == 0]
Out[26]:
In [27]:
{i%3 for i in range(10)}
Out[27]:
In [28]:
{i: i%3 for i in range(10)}
Out[28]:
In [29]:
(i**2 for i in range(10,15))
Out[29]:
In [30]:
for x in (i**2 for i in range(10,15)):
print(x)
In [31]:
# Note that count can generate an infinite stream
def count(i=0):
while True:
yield i
i += 1
In [32]:
c = count()
next(c)
Out[32]:
In [33]:
next(c)
Out[33]:
In [34]:
next(c)
Out[34]:
In [35]:
list(zip('abcde', count(10)))
Out[35]:
In [36]:
for i in count():
print(i)
if i >= 10:
break
In [37]:
def palindrome_numbers(n):
yield from range(1, n+1)
yield from range(n, 0, -1)
In [38]:
list(palindrome_numbers(5))
Out[38]:
In [39]:
import itertools as it
In [40]:
for i in it.islice(count(), 5, 10):
print(i)
In [41]:
for i in it.takewhile(lambda i: i< 5, count()):
print(i)
In [42]:
import operator as op
[i for i in it.starmap(op.add, [(1,2), (2,3), (3,4)])]
Out[42]:
In [43]:
fruits = ['appple', 'banana', 'cherry', 'durain', 'eggplant', 'fig']
for k, group in it.groupby(sorted(fruits, key=len), len):
print(k, list(group))
In [44]:
import functools as fn
In [45]:
rng1 = fn.partial(np.random.normal, 2, .3)
rng2 = fn.partial(np.random.normal, 10, 1)
In [46]:
rng1(10)
Out[46]:
In [47]:
rng2(10)
Out[47]:
In [48]:
fn.reduce(op.add, rng2(10))
Out[48]:
In [49]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
In [50]:
from pandas import DataFrame, Series
import scipy.stats as ss
In [51]:
DataFrame(ss.beta(2,5).rvs((3,4)), columns=['a', 'b', 'c', 'd'])
Out[51]:
In [52]:
import sys
sys.path
Out[52]:
In [53]:
%%file my_module.py
PI = 3.14
def my_f(x):
return PI*x
In [54]:
import my_module as mm
mm.PI
Out[54]:
In [55]:
mm.my_f(2)
Out[55]:
In [56]:
from my_module import PI
In [57]:
PI * 2 * 2
Out[57]:
Note: Modules can also be nested within each other - e.g. numpy.random
to creaate a package. We will explore how to create packages in a later session.