Python intro, cont'd.

Functions


In [1]:
def addme(x, y):
    return x + y

In [2]:
addme(4)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-4a0fd7b555df> in <module>()
----> 1 addme(4)

TypeError: addme() missing 1 required positional argument: 'y'

In [3]:
addme(2,3)


Out[3]:
5

In [4]:
def addme2(x, y=2):
    return x + y

In [5]:
addme2(5)


Out[5]:
7

In [6]:
addme2(5, y=10)


Out[6]:
15

In [7]:
addme2(x=6, y=10)


Out[7]:
16

In [8]:
addme2(y=10, x=6)


Out[8]:
16

In [41]:
d = dict(x=20, y=30)
addme2(**d)


Out[41]:
50

In [9]:
addme2(4,5)


Out[9]:
9

In [10]:
def myfunc(*args, **kwargs):
    print(args)
    print(kwargs)

In [11]:
myfunc(1,2,3,4,5)


(1, 2, 3, 4, 5)
{}

In [12]:
myfunc(1,2,3, a=10, b=20)


(1, 2, 3)
{'a': 10, 'b': 20}

In [37]:
def myplot(x, y, **kwargs):
    # Do some stuff
    # ...
    
    newx = x*10
    newy = y*100
    
    print(kwargs)
    
    plt.plot(newx, newy, **kwargs)

In [38]:
# Don't try the following line in python
%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
y = np.arange(10)

In [39]:
x, y


Out[39]:
(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

In [40]:
myplot(x, y, color='red', lw=5)


{'color': 'red', 'lw': 5}

In [31]:
x


Out[31]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [32]:
y


Out[32]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Classes


In [42]:
s = 'timothy d. morton'
type(s)


Out[42]:
str

In [43]:
s.split()


Out[43]:
['timothy', 'd.', 'morton']

In [44]:
s.upper()


Out[44]:
'TIMOTHY D. MORTON'

In [67]:
from math import sqrt

class Coord(object):
    def __init__(self, x, y):
        print('I am running the constructor!')
        self.x = x
        self.y = y
        
    def distance_from_origin(self):
        return sqrt(self.x**2 + self.y**2)

    def __add__(self, other):
        assert type(other) is Coord, 'Must add another Coord'
    
        newx = self.x + other.x
        newy = self.y + other.y
        return Coord(newx, newy)

In [68]:
c = Coord(4,5)


I am running the constructor!

In [69]:
c + 2


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-69-82cae4d4fa58> in <module>()
----> 1 c + 2

<ipython-input-67-a8656ba1fce6> in __add__(self, other)
     12 
     13     def __add__(self, other):
---> 14         assert type(other) is Coord, 'Must add another Coord'
     15 
     16         newx = self.x + other.x

AssertionError: Must add another Coord

In [71]:
c2 = Coord(10,20)
c3 = c + c2


I am running the constructor!
I am running the constructor!

In [73]:
c3.x, c3.y


Out[73]:
(14, 25)

In [55]:
c.x, c.y


Out[55]:
(4, 5)

In [56]:
type(c)


Out[56]:
__main__.Coord

In [57]:
c.distance_from_origin()


Out[57]:
6.4031242374328485

In [58]:
c + 2


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-58-82cae4d4fa58> in <module>()
----> 1 c + 2

TypeError: unsupported operand type(s) for +: 'Coord' and 'int'

Math


In [74]:
pi


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-74-68f7b1e53523> in <module>()
----> 1 pi

NameError: name 'pi' is not defined

In [75]:
sin(1)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-75-93e746b069d9> in <module>()
----> 1 sin(1)

NameError: name 'sin' is not defined

In [76]:
import math
math.pi


Out[76]:
3.141592653589793

In [77]:
math.sin(math.pi)


Out[77]:
1.2246467991473532e-16

In [78]:
from math import pi
pi


Out[78]:
3.141592653589793

In [79]:
from math import *

In [80]:
log


Out[80]:
<function math.log>

In [81]:
asin


Out[81]:
<function math.asin>

In [82]:
sin = 7

In [83]:
sin(0.5)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-83-898ffca1533c> in <module>()
----> 1 sin(0.5)

TypeError: 'int' object is not callable

numpy (math with arrays)


In [84]:
mylist = [1,2,3,4,5]

In [86]:
mylist*2


Out[86]:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

In [87]:
list2 = ['a', 'b', 'c']
mylist + list2


Out[87]:
[1, 2, 3, 4, 5, 'a', 'b', 'c']

In [89]:
import numpy as np

In [90]:
myarr = np.array(mylist)

In [91]:
myarr


Out[91]:
array([1, 2, 3, 4, 5])

In [92]:
myarr + 3


Out[92]:
array([4, 5, 6, 7, 8])

In [93]:
myarr * 100


Out[93]:
array([100, 200, 300, 400, 500])

In [94]:
myarr**2


Out[94]:
array([ 1,  4,  9, 16, 25])

In [95]:
np.arange(10)


Out[95]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [96]:
np.arange(10, 20, 2)


Out[96]:
array([10, 12, 14, 16, 18])

In [97]:
np.linspace(50, 60, 100)


Out[97]:
array([ 50.        ,  50.1010101 ,  50.2020202 ,  50.3030303 ,
        50.4040404 ,  50.50505051,  50.60606061,  50.70707071,
        50.80808081,  50.90909091,  51.01010101,  51.11111111,
        51.21212121,  51.31313131,  51.41414141,  51.51515152,
        51.61616162,  51.71717172,  51.81818182,  51.91919192,
        52.02020202,  52.12121212,  52.22222222,  52.32323232,
        52.42424242,  52.52525253,  52.62626263,  52.72727273,
        52.82828283,  52.92929293,  53.03030303,  53.13131313,
        53.23232323,  53.33333333,  53.43434343,  53.53535354,
        53.63636364,  53.73737374,  53.83838384,  53.93939394,
        54.04040404,  54.14141414,  54.24242424,  54.34343434,
        54.44444444,  54.54545455,  54.64646465,  54.74747475,
        54.84848485,  54.94949495,  55.05050505,  55.15151515,
        55.25252525,  55.35353535,  55.45454545,  55.55555556,
        55.65656566,  55.75757576,  55.85858586,  55.95959596,
        56.06060606,  56.16161616,  56.26262626,  56.36363636,
        56.46464646,  56.56565657,  56.66666667,  56.76767677,
        56.86868687,  56.96969697,  57.07070707,  57.17171717,
        57.27272727,  57.37373737,  57.47474747,  57.57575758,
        57.67676768,  57.77777778,  57.87878788,  57.97979798,
        58.08080808,  58.18181818,  58.28282828,  58.38383838,
        58.48484848,  58.58585859,  58.68686869,  58.78787879,
        58.88888889,  58.98989899,  59.09090909,  59.19191919,
        59.29292929,  59.39393939,  59.49494949,  59.5959596 ,
        59.6969697 ,  59.7979798 ,  59.8989899 ,  60.        ])

In [99]:
np.arange(50, 60, 0.05)


Out[99]:
array([ 50.  ,  50.05,  50.1 ,  50.15,  50.2 ,  50.25,  50.3 ,  50.35,
        50.4 ,  50.45,  50.5 ,  50.55,  50.6 ,  50.65,  50.7 ,  50.75,
        50.8 ,  50.85,  50.9 ,  50.95,  51.  ,  51.05,  51.1 ,  51.15,
        51.2 ,  51.25,  51.3 ,  51.35,  51.4 ,  51.45,  51.5 ,  51.55,
        51.6 ,  51.65,  51.7 ,  51.75,  51.8 ,  51.85,  51.9 ,  51.95,
        52.  ,  52.05,  52.1 ,  52.15,  52.2 ,  52.25,  52.3 ,  52.35,
        52.4 ,  52.45,  52.5 ,  52.55,  52.6 ,  52.65,  52.7 ,  52.75,
        52.8 ,  52.85,  52.9 ,  52.95,  53.  ,  53.05,  53.1 ,  53.15,
        53.2 ,  53.25,  53.3 ,  53.35,  53.4 ,  53.45,  53.5 ,  53.55,
        53.6 ,  53.65,  53.7 ,  53.75,  53.8 ,  53.85,  53.9 ,  53.95,
        54.  ,  54.05,  54.1 ,  54.15,  54.2 ,  54.25,  54.3 ,  54.35,
        54.4 ,  54.45,  54.5 ,  54.55,  54.6 ,  54.65,  54.7 ,  54.75,
        54.8 ,  54.85,  54.9 ,  54.95,  55.  ,  55.05,  55.1 ,  55.15,
        55.2 ,  55.25,  55.3 ,  55.35,  55.4 ,  55.45,  55.5 ,  55.55,
        55.6 ,  55.65,  55.7 ,  55.75,  55.8 ,  55.85,  55.9 ,  55.95,
        56.  ,  56.05,  56.1 ,  56.15,  56.2 ,  56.25,  56.3 ,  56.35,
        56.4 ,  56.45,  56.5 ,  56.55,  56.6 ,  56.65,  56.7 ,  56.75,
        56.8 ,  56.85,  56.9 ,  56.95,  57.  ,  57.05,  57.1 ,  57.15,
        57.2 ,  57.25,  57.3 ,  57.35,  57.4 ,  57.45,  57.5 ,  57.55,
        57.6 ,  57.65,  57.7 ,  57.75,  57.8 ,  57.85,  57.9 ,  57.95,
        58.  ,  58.05,  58.1 ,  58.15,  58.2 ,  58.25,  58.3 ,  58.35,
        58.4 ,  58.45,  58.5 ,  58.55,  58.6 ,  58.65,  58.7 ,  58.75,
        58.8 ,  58.85,  58.9 ,  58.95,  59.  ,  59.05,  59.1 ,  59.15,
        59.2 ,  59.25,  59.3 ,  59.35,  59.4 ,  59.45,  59.5 ,  59.55,
        59.6 ,  59.65,  59.7 ,  59.75,  59.8 ,  59.85,  59.9 ,  59.95])

In [100]:
np.zeros(5)


Out[100]:
array([ 0.,  0.,  0.,  0.,  0.])

In [101]:
np.ones(5)


Out[101]:
array([ 1.,  1.,  1.,  1.,  1.])

In [102]:
10*np.ones(5)


Out[102]:
array([ 10.,  10.,  10.,  10.,  10.])

In [105]:
np.zeros((3,4))


Out[105]:
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

In [106]:
np.arange(12).reshape((3,4))


Out[106]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [108]:
x = np.arange(12)
x.reshape((3,4))


Out[108]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Here's a little "gotcha":


In [114]:
x = np.arange(10)
y = x  # be sure you know what this line does!
x, y


Out[114]:
(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

In [115]:
y[5] = 100

In [116]:
x


Out[116]:
array([  0,   1,   2,   3,   4, 100,   6,   7,   8,   9])

In [117]:
x = np.arange(10)
y = x.copy()
y[5] = 100
x, y


Out[117]:
(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
 array([  0,   1,   2,   3,   4, 100,   6,   7,   8,   9]))

In [118]:
type(x)


Out[118]:
numpy.ndarray

In [119]:
x = [1,2,3,4,5]
y = x
y[2] = 100
x, y


Out[119]:
([1, 2, 100, 4, 5], [1, 2, 100, 4, 5])

Let's discuss indexing!


In [123]:
x = np.random.random(10)

In [124]:
x


Out[124]:
array([ 0.89413272,  0.34903165,  0.47309184,  0.76168118,  0.98309439,
        0.84076949,  0.64242618,  0.23401556,  0.32785939,  0.39153458])

In [125]:
x[2]


Out[125]:
0.47309184095421686

In [126]:
x[2:5]


Out[126]:
array([ 0.47309184,  0.76168118,  0.98309439])

In [127]:
x[-1]


Out[127]:
0.39153457735323971

In [129]:
x[1:-1]


Out[129]:
array([ 0.34903165,  0.47309184,  0.76168118,  0.98309439,  0.84076949,
        0.64242618,  0.23401556,  0.32785939])

In [130]:
trim = 2
x[trim: -1*trim]


Out[130]:
array([ 0.47309184,  0.76168118,  0.98309439,  0.84076949,  0.64242618,
        0.23401556])

In [131]:
x = np.random.random((4,5))

In [132]:
x


Out[132]:
array([[ 0.8348854 ,  0.61869336,  0.27457545,  0.79887015,  0.82652467],
       [ 0.01251086,  0.96670928,  0.26280421,  0.15923323,  0.70709163],
       [ 0.06514461,  0.32882251,  0.72512194,  0.75844255,  0.68482091],
       [ 0.45716787,  0.83704952,  0.03304868,  0.63298665,  0.40129791]])

In [133]:
x[1, 3]


Out[133]:
0.15923323201627193

In [135]:
x[0:2, 0:2]


Out[135]:
array([[ 0.8348854 ,  0.61869336],
       [ 0.01251086,  0.96670928]])

In [136]:
x[:, 1]


Out[136]:
array([ 0.61869336,  0.96670928,  0.32882251,  0.83704952])

In [137]:
y = x[0:2, 0:2] # this does not copy data! just returns a "view"
y


Out[137]:
array([[ 0.8348854 ,  0.61869336],
       [ 0.01251086,  0.96670928]])

In [138]:
y[0,0] = 100
y


Out[138]:
array([[  1.00000000e+02,   6.18693361e-01],
       [  1.25108617e-02,   9.66709280e-01]])

In [139]:
x


Out[139]:
array([[  1.00000000e+02,   6.18693361e-01,   2.74575453e-01,
          7.98870147e-01,   8.26524674e-01],
       [  1.25108617e-02,   9.66709280e-01,   2.62804211e-01,
          1.59233232e-01,   7.07091630e-01],
       [  6.51446139e-02,   3.28822509e-01,   7.25121942e-01,
          7.58442551e-01,   6.84820910e-01],
       [  4.57167870e-01,   8.37049523e-01,   3.30486845e-02,
          6.32986648e-01,   4.01297913e-01]])

In [140]:
np.shares_memory(x, y)


Out[140]:
True

In [141]:
x = np.random.random(10)
x


Out[141]:
array([ 0.2468686 ,  0.79704177,  0.60903853,  0.04350456,  0.10141312,
        0.2275861 ,  0.84394256,  0.56130802,  0.81799537,  0.90666407])

In [143]:
x > 0.5


Out[143]:
array([False,  True,  True, False, False, False,  True,  True,  True,  True], dtype=bool)

In [144]:
(x > 0.5).sum()


Out[144]:
6

In [145]:
sum(x > 0.5)


Out[145]:
6

In [146]:
x[x < 0.3]


Out[146]:
array([ 0.2468686 ,  0.04350456,  0.10141312,  0.2275861 ])

In [147]:
mask = x < 0.3
x[mask]


Out[147]:
array([ 0.2468686 ,  0.04350456,  0.10141312,  0.2275861 ])

In [150]:
np.where(x < 0.3)


Out[150]:
(array([0, 3, 4, 5]),)

In [151]:
w = np.where(x < 0.3)
x[w]


Out[151]:
array([ 0.2468686 ,  0.04350456,  0.10141312,  0.2275861 ])

In [149]:
x[[1,3,5,6]]


Out[149]:
array([ 0.79704177,  0.04350456,  0.2275861 ,  0.84394256])

matplotlib (plotting)

This command allows the plots to show up in the notebook (not a python command!):


In [110]:
%matplotlib inline

In [111]:
import matplotlib.pyplot as plt

In [112]:
x = np.linspace(0, 1, 100)
y = x**2
plt.plot(x, y)


Out[112]:
[<matplotlib.lines.Line2D at 0x11692c080>]

In [122]:
x = 5
y = x
y = 6
x, y


Out[122]:
(5, 6)

In [152]:
import re

In [153]:
s = 'hello, how are you?'

In [154]:
words = s.split()

In [155]:
words


Out[155]:
['hello,', 'how', 'are', 'you?']

In [161]:
m = re.search('\w+', words[0])

In [162]:
m.group(0)


Out[162]:
'hello'

In [158]:
s = 'abcbca'
m = re.search('b(cb)', s)

In [159]:
m.group(0)


Out[159]:
'bcb'

In [160]:
m.group(1)


Out[160]:
'cb'

In [165]:
m = re.search('\w+', "it's")
m.group(0)


Out[165]:
'it'

In [ ]:
^ $