In [2]:
from math import sqrt

def fibo1(n): # Recursive Fibonacci number
    if n == 0:
        return 0
    elif n == 1:
        return 1
    return fibo1(n-1) + fibo1(n-2)

def fibo2(n): # Closed Form
    return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))

In [3]:
%timeit fibo1(20)


100 loops, best of 3: 3.55 ms per loop

In [4]:
%timeit fibo2(20)


The slowest run took 14.23 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 921 ns per loop

In [6]:
import random

In [7]:
%%timeit
prize = 0
for ii in range(100):
    # roll a die
    roll = random.randint(1, 6)
    if roll % 2 == 0:
        prize += roll
    else:
        prize -= 1


10000 loops, best of 3: 152 µs per loop

In [8]:
%%timeit
rolls = (random.randint(1, 6) for _ in range(100))
prize = sum(roll if roll % 2 == 0 else -1 for roll in rolls)


10000 loops, best of 3: 158 µs per loop

Matplotlib visualizations!


In [10]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import matplotlib.pyplot as plt
import numpy as np

In [11]:
x = np.linspace(0, 1, 300)
for w in range(2, 6, 2):
    plt.plot(x, np.sin(np.pi*x) * np.sin(2*w*np.pi*x))


Debugging


In [12]:
%pdb


Automatic pdb calling has been turned ON

In [ ]:
numbers = 'hello'
sum(numbers)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-7a179164921f> in <module>()
      1 numbers = 'hello'
----> 2 sum(numbers)

TypeError: unsupported operand type(s) for +: 'int' and 'str'
> <ipython-input-13-7a179164921f>(2)<module>()
      1 numbers = 'hello'
----> 2 sum(numbers)