Chapter 1: Computing with Python

Robert Johansson

Source code listings for Numerical Python - A Practical Techniques Approach for Industry (ISBN 978-1-484205-54-9).

The source code listings can be downloaded from http://www.apress.com/9781484205549

Interpreter

In [1]:
%%writefile hello.py
print("Hello from Python!")
Overwriting hello.py
In [2]:
!python hello.py
Hello from Python!
In [3]:
!python --version
Python 2.7.10 :: Continuum Analytics, Inc.

Input and output caching

In [1]:
3 * 3
Out[1]:
9
In [2]:
In[1]
Out[2]:
u'3 * 3'
In [3]:
Out[1]
Out[3]:
9
In [4]:
In
Out[4]:
['', u'3 * 3', u'In[1]', u'Out[1]', u'In']
In [5]:
Out
Out[5]:
{1: 9,
 2: u'3 * 3',
 3: 9,
 4: ['', u'3 * 3', u'In[1]', u'Out[1]', u'In', u'Out']}
In [6]:
1+2
Out[6]:
3
In [7]:
1+2;
In [8]:
x = 1
In [9]:
x = 2; x
Out[9]:
2

Documentation

In [10]:
import os
In [11]:
# try os.w<TAB>
In [12]:
import math
In [13]:
math.cos?

Interaction with System Shell

In [14]:
!touch file1.py file2.py file3.py
In [15]:
!ls file*
file1.py file2.py file3.py
In [16]:
files = !ls file*
In [17]:
len(files)
Out[17]:
3
In [18]:
files
Out[18]:
['file1.py', 'file2.py', 'file3.py']
In [19]:
file = "file1.py"
In [20]:
!ls -l $file
-rw-r--r--  1 rob  staff  0 Aug 30 17:03 file1.py

Running scripts from the IPython console

In [21]:
%%writefile fib.py

def fib(N): 
    """ 
    Return a list of the first N Fibonacci numbers.
    """ 
    f0, f1 = 0, 1
    f = [1] * N
    for n in range(1, N):
        f[n] = f0 + f1
        f0, f1 = f1, f[n]

    return f

print(fib(10))
Overwriting fib.py
In [22]:
!python fib.py
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
In [23]:
%run fib.py
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
In [24]:
fib(6)
Out[24]:
[1, 1, 2, 3, 5, 8]

Debugger

In [25]:
fib(1.0)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-ccc1774a65b9> in <module>()
----> 1 fib(1.0)

/Users/rob/Desktop/apress-numerical-python-review/code/fib.py in fib(N)
      5     """ 
      6     f0, f1 = 0, 1
----> 7     f = [1] * N
      8     for n in range(1, N):
      9         f[n] = f0 + f1

TypeError: can't multiply sequence by non-int of type 'float'
In [26]:
%debug
> /Users/rob/Desktop/apress-numerical-python-review/code/fib.py(7)fib()
      6     f0, f1 = 0, 1
----> 7     f = [1] * N
      8     for n in range(1, N):

ipdb> print(N)
1.0
ipdb> q

Timing and profiling code

In [27]:
%timeit fib(100)
100000 loops, best of 3: 18.2 µs per loop
In [28]:
result = %time fib(100)
CPU times: user 38 µs, sys: 22 µs, total: 60 µs
Wall time: 47 µs
In [29]:
len(result)
Out[29]:
100
In [30]:
import numpy as np

def random_walker_max_distance(M, N):
    """
    Simulate N random walkers taking M steps, and return the largest distance
    from the starting point achieved by any of the random walkers.
    """
    trajectories = [np.random.randn(M).cumsum() for _ in range(N)]
    return np.max(np.abs(trajectories))
In [31]:
%prun random_walker_max_distance(400, 10000)
 

IPython nbconvert

In [32]:
!ipython nbconvert --to html ch01-code-listing.ipynb
[NbConvertApp] Converting notebook ch01-code-listing.ipynb to html
[NbConvertApp] Writing 219405 bytes to ch01-code-listing.html
In [33]:
!ipython nbconvert --to pdf ch01-code-listing.ipynb
[NbConvertApp] Converting notebook ch01-code-listing.ipynb to pdf
[NbConvertApp] Writing 25971 bytes to notebook.tex
[NbConvertApp] Building PDF
[NbConvertApp] Running pdflatex 3 times: [u'pdflatex', u'notebook.tex']
[NbConvertApp] PDF successfully created
[NbConvertApp] Writing 114085 bytes to ch01-code-listing.pdf
In [34]:
%%writefile custom_template.tplx
((*- extends 'article.tplx' -*))

((* block title *)) \title{Document title} ((* endblock title *))
((* block author *)) \author{Author's Name} ((* endblock author *))
Overwriting custom_template.tplx
In [35]:
!ipython nbconvert ch01-code-listing.ipynb --to pdf --template custom_template.tplx
[NbConvertApp] Converting notebook ch01-code-listing.ipynb to pdf
[NbConvertApp] Writing 25994 bytes to notebook.tex
[NbConvertApp] Building PDF
[NbConvertApp] Running pdflatex 3 times: [u'pdflatex', u'notebook.tex']
[NbConvertApp] PDF successfully created
[NbConvertApp] Writing 114961 bytes to ch01-code-listing.pdf
In [36]:
!ipython nbconvert ch01-code-listing.ipynb --to python
[NbConvertApp] Converting notebook ch01-code-listing.ipynb to python
[NbConvertApp] Writing 3237 bytes to ch01-code-listing.py

Versions

In [37]:
%reload_ext version_information
%version_information numpy
Out[37]:
SoftwareVersion
Python2.7.10 64bit [GCC 4.2.1 (Apple Inc. build 5577)]
IPython4.0.0
OSDarwin 14.5.0 x86_64 i386 64bit
numpy1.9.2