Python, Part 1
Python, Part 1
Python: part I
Advanced Research Computing
Outline
• A tour of Python
– Date types, exceptions
– Functions, modules, generators
– Functional programming
– The Map-reduce data-parallel pattern
• Linear algebra in Python
– Saxpy as a map operation
– Using C extensions from Python
• Data-parallel Python
Advanced Research Computing
2
A TOUR OF PYTHON
t1 = (); t2 = (1, );
t3 = tuple(‘hello’); t3[0]; t3[-1]
a=1, b=2; a,b = (b, a)
l3 = list(t3)
Advanced Research Computing
Lists
• Lists are mutable, heterogeneous sequences
l0= [];
l1 = [1, 2, 3.14, 9.81]; l2 = range(4);
l1.index(3.14); l1.count(2)
del l1[3]; l1.remove(3.14); l1.append(4.5)
# okay for list, but not for tuple
l1[2] = 3; l1[2:] = (3,4)
pairs = zip(l1, l2)
l1_l2 = l1 + l2; l2x2 = l2 * 2
l3 = list(t3); l3[0]; l3[-1]; l3[1:]
len(l3); type(l3)
Advanced Research Computing
Sets
• Sets are unordered collections of immutable
objects (ints, floats, strings, tuples)
s1 = set([1, 2, 3, 4 ])
s1.add(6); s1.add(5)
s2 = set([1, 2, 3, 4, 5, 4,3,2,1]
s1 | s2; s1 & s2; s1 ^ s2
s3 = frozenset( set([5]) )
s1.add(s3)
Advanced Research Computing
Dictionaries
• Python’s associative arrays
e2f= {}
e2f = { ‘blue’: ‘bleu’, ‘red’: rouge}
e2f[‘green’] = ‘vert’
e2f[‘blue’]; e2f.get(‘blue’)
‘red’ in e2f; del e2f[‘green’]
list(e2f.keys()); list(e2f.values());
list(e2f.items()); len(e2f)
num = { 1: ‘one’, 2: ‘two’}; num1 =num.copy()
Advanced Research Computing
Iterables
• An iterable is an object that has an iterator
– The iterator is obtained with the __iter__()
method or with the iter() function
– can be iterated through with the construct:
for item in iterable
• Lists and tuples are iterable objects, but there
are others
– NumPy arrays ;
– Generator objects
• Some functions (e.g., sum) require an iterable
Advanced Research Computing
Control Flow
• If, for, and while
x = [ -1, 2, 3] ; i = 0
for el in x:
if x < 0:
print ‘negative’
elif x== 0:
print ‘zero’
else:
print ‘positive’
while (i < len(x)):
print x[i]; i += 1
Advanced Research Computing
Functions
• Functions have dynamically typed arguments
• The number of function arguments can be
fixed or variable
– The function definition indicates whether it
accepts a variable number of arguments
• Recursive vs iterative function implementation
– Cost of function call + if statement vs cost of for
loop
– Example the factorial function
def factorial_rec(n):
if ( n <= 1):
return 1
else:
return n * factorial_rec(n – 1)
print factorial_rec(4)
list = range(8)
show_list( list); show_list( list, 4); show_list( list, 4, 2)
reciprocals(3)
Advanced Research Computing
Classes
• Every class has the __init__() method - constructor
• Every method has as first parameter self, which is a
reference to the class instance
• Private instance variables can be accessed only from
inside the object
class Circle:
def __init__(self, radius=1):
self.__radius = radius
def get_radius(self):
return self.__radius
def set_radius(self, radius):
self.__radius = radius
Advanced Research Computing
Functional Programming (1)
• Imperative programming
– Program seen as a sequence of computation steps
– Focus is on how to compute the solution of the
problem
• Functional programming
– Program seen as evaluations of mathematical
functions
– Focus is on what to compute to solve the problem
sum
map
reduce
Advanced Research Computing
LINEAR ALGEBRA IN PYTHON
mkl = cdll.LoadLibrary("libmkl_rt.so")
cblas_saxpy = mkl.cblas_saxpy
n = 8; alpha = 1.0
xp = c_float * n;
yp = c_float * n
x = xp(0.0); y = yp(0.0)
for i in range(len(x)):
x[i] = 1.0; y[i] = 1.0
cblas_saxpy( c_int(n), c_float(1.0), \
byref(x), c_int(1), byref(y), c_int(1))
n = 8; a = 1.0
x = np.ones(n, 'f')
y = np.ones(n, 'f')
x_i y_i
a*x_i + y_i
Questions?