We begin by importing scientific packages in the global namespace:
%pylab
Using matplotlib backend: MacOSX Populating the interactive namespace from numpy and matplotlib
We tell matplotlib
to plot inside this notebook.
%matplotlib inline
Shift+enter, help, save, %whos
, %pylab
, %debug
, text+Python, up-downloadable, Python notebook for matlab users, Nature article, nonlinear evaluation
a = 3
b = 10
Operations (*
,+
,-
,**
,/
), and //
. Operations %
, int
?
i = 3
print(i)
3
i
3
Out[7] + 10
13
type(i)
int
%whos
Variable Type Data/Info ---------------------------- a int 3 b int 10 i int 3
f = 2.3
type(f)
float
f + i
5.3
print(type(1))
print(type(1.))
<class 'int'> <class 'float'>
z = 1. + 2.j
print(z)
(1+2j)
J = 1.j
2 + 3*J
(2+3j)
type(2+3j)
complex
z
(1+2j)
z.real
1.0
z.imag
2.0
z.conjugate()
(1-2j)
%whos
Variable Type Data/Info ------------------------------- J complex 1j a int 3 b int 10 f float 2.3 i int 3 z complex (1+2j)
f * i
6.8999999999999995
f + i
5.3
2^3
1
2**3
8
2/3
0.6666666666666666
2//3
0
10//4
2
print(10.1//4.1)
print(floor(10.1/4.1))
2.0 2.0
# comment
pi
3.141592653589793
Double, single quotes, triple, escape (\
), concatenation (+
), interpolation (%
, format
)
s = "hello "
me = "Olivier"
s + me
'hello Olivier'
template = "Hello {}, my name is {}"
template.format("Olivier", "Jupyter")
'Hello Olivier, my name is Jupyter'
template.format("Åsa")
'Hello Åsa'
s_ = 'single quotes instead'
s__ = "I'm happy"
print(s)
print(s__)
hello I'm happy
s = """Three quotes
with return inside
another one
"""
s = "hello, \nI'm happy"
print(s)
hello, I'm happy
def
, name, parameters, colon :
, indentation block, return
, execution with ()
, pass function around
def my_function(param):
print(param)
return 3
a = my_function("argument")
argument
a
3
def add_prod(x1, x2):
"""This is a nice function,
which computes add and product of
two numbers"""
return x1 + x2, x1*x2
add_prod?
r = add_prod(2,3)
print(r)
(5, 6)
r[0]
5
r[1]
6
print(s,p)
5 6
def greetings(name):
template = "Hello {}, how are you??"
print(template)
print("still in function")
print("I'm outside the function")
I'm outside the function
greetings(3)
'Hello 3, how are you??'
def print_greetings():
print("Hi!")
def compute():
x = 2 + 5
return x
def post_process(x):
return x + 10
post_process(compute())
17
x = print_greetings
print(x)
<function print_greetings at 0x1072856a8>
x()
Hi!
print_greetings() # function execution
Hi!
print_greetings # just the function
<function __main__.print_greetings>
def execute(f):
f()
execute(print_greetings)
Hi!
x = print_greetings
x()
def get_number():
return 2.
y = get_number
y + 2
"2" + 3
2. + 3
x = 2.
x.__add__(3)
step function (plot+vectorize
?), comparison ops ==
, !=
, <
, >
, <=
, >=
. Logical ops not
, and
, or
, bool
def sign(x):
if x > 0:
# several instructions here
return 1.
elif x > -1:
return 0.
else:
return -1
def inside(x):
if (x < 0) and (x > -1):
return "fantastic"
else:
return "too bad"
inside(-.5)
'fantastic'
2 > 3 or 10 > 5
True
not 3 < 5
False
sign(-.5)
0.0
sign(3)
1.0
sign(-1)
-1.0
[]
, accessing (from zero!), altering, append
, len
, concatenate +
, and *
, slicing :
, last element -1
L = [2, 3, 4]
L[0]
2
L[1]
3
len(L)
3
L.append(10)
print(L)
[2, 3, 4, 10]
L.append("hello")
print(L)
[2, 3, 4, 10, 'hello']
L[4] = 11
print(L)
[2, 3, 4, 10, 11]
L[-1]
11
L[-2]
10
L[-0]
2
L
[2, 3, 4, 10, 11]
L[1:4]
[3, 4, 10]
L[1:-1]
[3, 4, 10]
L[2:-1]
[4, 10]
L[1:-2]
[3, 4]
L[1:-1:2]
[3, 10]
L
[2, 3, 4, 10, 11]
L[::-2]
[11, 4, 2]
Lm = ["Good bye", 3, print_greetings]
L[i:j]
means take i-j
elements, starting at i
included
middle = len(Lb)//2
print(middle)
print(Lb[:middle])
print(Lb[middle:])
pseudo_matrix = [[1,2],[3,4]]
pseudo_matrix[0][1]
for i in range(10):
if i > 5:
break
print(i)
0 1 2 3 4 5
L
[2, 3, 4, 10, 11]
for x in L:
print(x**2)
4 9 16 100 121
list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(10000000000000000000000000000)
range(0, 10000000000000000000000000000)
Pointers (two lists), Python tutor? args by reference, copy with list
, deep copy?, is
, tuples
L = [2,3,4]
L_ = L
L_[0] = 100
print(L_)
[100, 3, 4]
print(L)
[100, 3, 4]
print(L)
[100, 3, 4]
print(L_)
[100, 3, 4]
L is L_
True
L_copy = L[:]
print(L_copy)
[100, 3, 4]
L is L_copy
False
import copy
copy.deepcopy
L.sort()
L
[2, 3, 4, 10]
L.reverse()
L
[10, 4, 3, 2]
y = 10
def add_y(x):
y = 100
return x + y
add_y(100)
200
y
10
add_y(100)
120
L = [2,3,4]
add_10(L)
L
[2, 3, 4, 10]
L + L
[10, 4, 3, 2, 10, 4, 3, 2]
array
, vectors, matrices, shape, access [3,4]
, difference with lists, no append, concatenate
Difference vector matrices
V = array([2.,3.,4])
V + V
array([ 4., 6., 8.])
M = array([[2,.3],[1,4]])
print(M)
[[ 2. 0.3] [ 1. 4. ]]
V
array([ 2., 3., 4.])
V[0]
2.0
M[0,0]
2.0
V
array([ 2., 3., 4.])
V * V
array([ 4., 9., 16.])
shape(V)
(3,)
CV = array([[2.],[3.],[4.]])
print(CV)
[[ 2.] [ 3.] [ 4.]]
shape(CV)
(3, 1)
RV = array([[2.,3,4]])
print(RV)
[[ 2. 3. 4.]]
shape(RV)
(1, 3)
row_0 = [3,4,5.]
M = array([row_0])
print(M)
[[ 3. 4. 5.]]
shape(M)
(1, 3)
V
array([ 2., 3., 4.])
V.reshape((1,3))
array([[ 2., 3., 4.]])
M = V.reshape((3,1))
array([[ 2.], [ 3.], [ 4.]])
T = arange(8).reshape((2,2,2))
print(T)
[[[0 1] [2 3]] [[4 5] [6 7]]]
arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
array(list(range(10)))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
concatenate
pointwise operations,
dot
,
M = arange(4).reshape((2,2))
print(M)
[[0 1] [2 3]]
V = array([2,3])
M*V # NOT matrix vector multiplication!!!
array([[0, 3], [4, 9]])
dot(M,V)
array([ 3, 13])
dot(V,M)
array([ 6, 11])
dot(V,V)
13
CV = V.reshape((2,1))
dot(M,CV)
array([[ 3], [13]])
shape(CV)
(2, 1)
CV.T
array([[2, 3]])
shape(CV.T)
(1, 2)
shape(V)
(2,)
V.T
array([2, 3])
shape(V.T)
(2,)
V * V.reshape((2,1))
array([[4, 6], [6, 9]])
dot(CV,M)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-213-c40d19060ea6> in <module>() ----> 1 dot(CV,M) ValueError: shapes (2,1) and (2,2) not aligned: 1 (dim 1) != 2 (dim 0)
shape
, .shape
. [:,i]
. transpose
, .T
, vector transpose. shape
, reshape
, column & row matrices. reshape(-1)
.
(flags
?)
Array creation: zeros
, ones
, empty
, eye
(identity
)
zeros((2,3))
array([[ 0., 0., 0.], [ 0., 0., 0.]])
ones((3,2))
array([[ 1., 1.], [ 1., 1.], [ 1., 1.]])
identity(3) # eye(3)
array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]])
Solving linear systems. allclose
print(M)
print(V)
x = solve(M,V)
print(x)
print(dot(M,x))
print(V)
[[0 1] [2 3]] [2 3] [-1.5 2. ] [ 2. 3.] [2 3]
Slicing and shape
Concatenation with concatenate
, array
, block matrices together, vectors into row or columns.
same syntax, no hold, figure, axis('equal')
. title
, xlabel
, ylabel
, label
, legend
.
xs = linspace(0,2*pi,100)
ys = sin(xs)
zs = cos(3*xs)
plot(xs, ys, 'o')
plot(xs, zs, '.')
figure()
plot(xs, ys+.3*zs)
savefig('name.pdf')
plot(xs,ys)
figure()
plot(xs,zs)
plot?
0702683132