Lecturer:José Pedro Silva1 - silva_at_math.uni-wuppertal.de
from numpy import finfo, iinfo
import numpy as np
finfo(np.float128).eps
1.084202172485504434e-19
LOOPS
for i in [0,1,2,3,4,5]:
print i**2
0 1 4 9 16 25
for i in range(6):
print i**2
0 1 4 9 16 25
for i in xrange(6):
print i**2
0 1 4 9 16 25
from numpy import arange
%%timeit
from numpy import arange
for i in arange(100000000):
pass
--------------------------------------------------------------------------- KeyboardInterrupt Traceback (most recent call last) <ipython-input-4-fe251d2d3a0a> in <module>() ----> 1 get_ipython().run_cell_magic(u'timeit', u'', u'\nfrom numpy import arange\nfor i in arange(100000000):\n pass') /home/jpsilva/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in run_cell_magic(self, magic_name, line, cell) 2160 magic_arg_s = self.var_expand(line, stack_depth) 2161 with self.builtin_trap: -> 2162 result = fn(magic_arg_s, cell) 2163 return result 2164 /home/jpsilva/anaconda/lib/python2.7/site-packages/IPython/core/magics/execution.pyc in timeit(self, line, cell) /home/jpsilva/anaconda/lib/python2.7/site-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k) 191 # but it's overkill for just that one bit of state. 192 def magic_deco(arg): --> 193 call = lambda f, *a, **k: f(*a, **k) 194 195 if callable(arg): /home/jpsilva/anaconda/lib/python2.7/site-packages/IPython/core/magics/execution.pyc in timeit(self, line, cell) 1014 break 1015 number *= 10 -> 1016 all_runs = timer.repeat(repeat, number) 1017 best = min(all_runs) / number 1018 if not quiet : /home/jpsilva/anaconda/lib/python2.7/timeit.pyc in repeat(self, repeat, number) 221 r = [] 222 for i in range(repeat): --> 223 t = self.timeit(number) 224 r.append(t) 225 return r /home/jpsilva/anaconda/lib/python2.7/timeit.pyc in timeit(self, number) 193 gc.disable() 194 try: --> 195 timing = self.inner(it, self.timer) 196 finally: 197 if gcold: <magic-timeit> in inner(_it, _timer) KeyboardInterrupt:
%%timeit
for i in xrange(1000000000):
pass
--------------------------------------------------------------------------- KeyboardInterrupt Traceback (most recent call last) <ipython-input-1-e230d5d21e84> in <module>() ----> 1 get_ipython().run_cell_magic(u'timeit', u'', u'\nfor i in xrange(1000000000):\n pass') /home/jpsilva/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in run_cell_magic(self, magic_name, line, cell) 2160 magic_arg_s = self.var_expand(line, stack_depth) 2161 with self.builtin_trap: -> 2162 result = fn(magic_arg_s, cell) 2163 return result 2164 /home/jpsilva/anaconda/lib/python2.7/site-packages/IPython/core/magics/execution.pyc in timeit(self, line, cell) /home/jpsilva/anaconda/lib/python2.7/site-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k) 191 # but it's overkill for just that one bit of state. 192 def magic_deco(arg): --> 193 call = lambda f, *a, **k: f(*a, **k) 194 195 if callable(arg): /home/jpsilva/anaconda/lib/python2.7/site-packages/IPython/core/magics/execution.pyc in timeit(self, line, cell) 1014 break 1015 number *= 10 -> 1016 all_runs = timer.repeat(repeat, number) 1017 best = min(all_runs) / number 1018 if not quiet : /home/jpsilva/anaconda/lib/python2.7/timeit.pyc in repeat(self, repeat, number) 221 r = [] 222 for i in range(repeat): --> 223 t = self.timeit(number) 224 r.append(t) 225 return r /home/jpsilva/anaconda/lib/python2.7/timeit.pyc in timeit(self, number) 193 gc.disable() 194 try: --> 195 timing = self.inner(it, self.timer) 196 finally: 197 if gcold: <magic-timeit> in inner(_it, _timer) KeyboardInterrupt:
xrange is now range in Python3!
Looping over collections
colors = ['red','green','blue','yellow']
for i in range(len(colors)):
print colors[i]
red green blue yellow
for color in colors:
print color
red green blue yellow
Looping backwards
for i in range(len(colors)-1,-1,-1):
print colors[i]
yellow blue green red
for color in reversed(colors):
print color
yellow blue green red
Looping with indices
for i in range(len(colors)):
print i, '-->', colors[i]
0 --> red 1 --> green 2 --> blue 3 --> yellow
for i,color in enumerate(colors):
print i, '-->', color
0 --> red 1 --> green 2 --> blue 3 --> yellow
%%timeit
for i in range(len(colors)):
pass
1000000 loops, best of 3: 360 ns per loop
%%timeit
for i,color in enumerate(colors):
pass
1000000 loops, best of 3: 398 ns per loop
Looping over two collection
names = ['Ze','Pedro','Nicola','Jose','Filipe']
n = min(len(names), len(colors))
for i in range(n):
print names[i], '-->', colors[i]
Ze --> red Pedro --> green Nicola --> blue Jose --> yellow
for name,color in zip(names,colors):
print name,'-->', color
Ze --> red Pedro --> green Nicola --> blue Jose --> yellow
%%timeit
n = min(len(names), len(colors))
for i in range(n):
pass
# print names[i], '-->', colors[i]
1000000 loops, best of 3: 552 ns per loop
%%timeit
for name,color in zip(names,colors):
pass
# print name,'-->', color
1000000 loops, best of 3: 573 ns per loop
%%timeit
from itertools import izip
for name,color in izip(names,colors):
pass
# print name, '-->', color
1000000 loops, best of 3: 1.38 µs per loop
for color in sorted(colors, key=lambda x: len(x), reverse=True):
print color
yellow green blue red
partial?
Object `partial` not found.
d = {'Pólvora':'I','Silva':'II','Cantarutti':'III','Santos':'IV'}
%load_ext memory_profiler
%memit for i in range(100000000): pass
peak memory: 3137.62 MiB, increment: 3107.40 MiB
%memit for i in xrange(100000000): pass
peak memory: 2374.84 MiB, increment: 0.00 MiB
for k in d:
print k
Silva Pólvora Santos Cantarutti
for k in d:
print k, '-->', d[k]
Silva --> II Pólvora --> I Santos --> IV Cantarutti --> III
for k,v in d.items():
print k, '-->', v
Silva --> II Pólvora --> I Santos --> IV Cantarutti --> III
for k,v in d.iteritems():
print k, '-->', v
Silva --> II Pólvora --> I Santos --> IV Cantarutti --> III
from itertools import izip
d2 = dict(izip(names,colors))
d2
{'Jose': 'yellow', 'Nicola': 'blue', 'Pedro': 'green', 'Ze': 'red'}
Counting with dict
colors = ['red','blue','green','red','yellow','green']
d3 = {}
for color in colors:
if color not in d3:
d3[color] = 0
d3[color] += 1
d3
1000000 loops, best of 3: 1.01 µs per loop
d3 = {}
for color in colors:
d3[color] = d3.get(color,0) + 1
d3
1000000 loops, best of 3: 1.17 µs per loop
from collections import defaultdict
d3 = defaultdict(int)
for color in colors:
d3[color] += 1
d3 = dict(d3)
d3
1000000 loops, best of 3: 1.74 µs per loop
Group with dict
names = ['Ze','Pedro','Nicola','Jose','Filipe','Yasser','Maria','Gilson']
d = {}
for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)
d
{2: ['Ze'], 4: ['Jose'], 5: ['Pedro', 'Maria'], 6: ['Nicola', 'Filipe', 'Yasser', 'Gilson']}
d = {}
for name in names:
key = len(name)
d.setdefault(key, []).append(name)
d
{2: ['Ze'], 4: ['Jose'], 5: ['Pedro', 'Maria'], 6: ['Nicola', 'Filipe', 'Yasser', 'Gilson']}
d = defaultdict(list)
for name in names:
d[len(name)].append(name)
dict(d)
{2: ['Ze'], 4: ['Jose'], 5: ['Pedro', 'Maria'], 6: ['Nicola', 'Filipe', 'Yasser', 'Gilson']}
Unpacking sequences
data = 'Jose','Silva',28,'silva@math.uni-wuppertal.de'
fname = data[0]
lname = data[1]
age = data[2]
email = data[3]
print fname, lname, age, email
Jose Silva 28 silva@math.uni-wuppertal.de
fname, lname, _ = data
print fname, lname, age
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-41-755e818d6955> in <module>() ----> 1 fname, lname, _ = data 2 print fname, lname, age ValueError: too many values to unpack
Works specially well with points, for example
from numpy import *
p1 = (1,1)
x, y = p1
r, theta = sqrt(x**2+y**2), arctan(y/x)
print r,theta
1.41421356237 0.785398163397
The ugly, the map, and the list comprehensions
oldlist = ['eu','ich','i','io','yo','я']
newlist = []
for word in oldlist:
newlist.append(word.capitalize())
for word in newlist:
print word,
Eu Ich I Io Yo я
newlist = map(str.capitalize,oldlist)
for word in newlist:
print word,
Eu Ich I Io Yo я
newlist = [word.capitalize() for word in oldlist]
for word in newlist:
print word,
Eu Ich I Io Yo я
%%timeit
newlist = []
for word in oldlist:
newlist.append(word.capitalize())
1000000 loops, best of 3: 1.25 µs per loop
%timeit newlist = map(str.capitalize,oldlist)
%timeit newlist = [word.capitalize() for word in oldlist]
1000000 loops, best of 3: 977 ns per loop 1000000 loops, best of 3: 793 ns per loop
oldlist = [u'eu',u'ich',u'i',u'io',u'yo',u'я']
newlist = []
for word in oldlist:
newlist.append(word.capitalize())
for word in newlist:
print word,
print
newlist = [word.capitalize() for word in oldlist]
for word in newlist:
print word,
newlist = map(unicode.capitalize,oldlist)
for word in newlist:
print word,
Eu Ich I Io Yo Я Eu Ich I Io Yo Я Eu Ich I Io Yo Я
Sum of squares up to N
result = []
N = 10
for i in range(N):
s = i**2
result.append(s)
print sum(result)
285
%%timeit
sum([i**2 for i in range(N)])
100000 loops, best of 3: 7.88 µs per loop
%%timeit
sum([i**2 for i in xrange(N)])
100000 loops, best of 3: 7.42 µs per loop
%%timeit
sum(i**2 for i in xrange(N))
1000000 loops, best of 3: 1.63 µs per loop
import numpy as np
%%timeit
(np.arange(N,dtype=int)**2).sum()
100000 loops, best of 3: 3.12 µs per loop
Column Order
arr_c = np.ones((1000,1000),order='C')
arr_f = np.ones((1000,1000),order='F')
%timeit arr_c.sum(1)
1000 loops, best of 3: 625 µs per loop
%timeit arr_f.sum(1)
1000 loops, best of 3: 611 µs per loop
arr_f.flags
C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False
arr_c.flags
C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False
%reload_ext version_information
%version_information numpy
Software | Version |
---|---|
Python | 2.7.4 (default, Sep 26 2013, 03:20:56) [GCC 4.7.3] |
IPython | 1.1.0 |
OS | posix [linux2] |
numpy | 1.7.1 |
So Okt 06 15:27:18 2013 CEST |
from IPython.core.display import HTML
def css_styling():
styles = open("./styles/custom.css", "r").read()
return HTML(styles)
css_styling()