pickle
return
values to communicate their
resultsWorks analog to reading files
with open(filename, 'w', encoding='utf8') as f:
f.write(.)
f.writelines(.)
You may also redirect print
with open(filename, 'w', encoding='utf8') as f:
print(., file=f)
from os import linesep
# ... long computation
result = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
with open('result.txt', 'w', encoding='utf-8') as outfile: # w => write
outfile.write("These numbers solve the world's problems!" + linesep)
for row in result:
for elem in row:
outfile.write(str(elem) + ' ')
print(file=outfile)
Download write_file.py
Writing to the end of an existing file
from os import linesep
# ... long computation
result = [[1, 3, 2],
[4, 5, 6],
[9, 8, 7]]
with open('result.txt', 'a', encoding='utf-8') as outfile: # a => append
outfile.write("Now we really solve the world's problems!" + linesep)
for row in result:
for elem in row:
print(str(elem), file=outfile, end=' ')
outfile.write(linesep)
Download append_file.py
Danger: binary files are not human readable
Storing objects is easiest with pickle
import pickle
result = [[1, 3, 2],
[4, 5, 6],
[9, 8, 7]]
with open('test.dump', 'wb') as f: # wb or bw => write binary
pickle.dump(result, f)
Reading "pickled" objects is straightforward
import pickle
with open('test.dump', 'rb') as f: # rb or br => read binary
result = pickle.load(f)
Aka function constant, function literal, or lambda
function
lambda arg [, arg2, ...]: expression
The result of expression
is implicitly returned
It is possible to assign lambdas to identifiers
func = lambda x, y: x + y
result = func(3, 4)
Default sorting criterion: each sublist's first element
m = [[2, 'student', 'master'],
[3, 'student', 'bachelor'],
[1, 'works', 'full time']]
m.sort()
If versatile control is needed, lambdas can be used
m = [[2, 'student', 'master'],
[3, 'student', 'bachelor'],
[1, 'works', 'full time']]
m.sort(key=lambda x: x[2])
By default, strings are sorted by the unicode code points of their characters
Using lambdas allows more natural sorting
#!/usr/bin/env python3
names = ['betty', 'Anna', 'Sue', 'gernot', 'Luis', 'Therese', 'amelie', ]
names.sort() # likely not what we'd expect
names.sort(key=lambda x: x.lower())
Function calling itself
#!/usr/bin/env python3
def factorial(n):
"""
Return the factorial of n.
"""
assert n >= 0
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursion: use solution to smaller problem
print(factorial(5))
def fib(n):
"""
Return the n-th fibonacci number (starting at 1).
Note: this is an inefficient implementation.
"""
if n <= 1: # base case
return n
return fib(n - 1) + fib(n - 2) # recursive case
print(fib(5))
map
, filter
Examples of higher-order functions
For efficiency, both return iterators yielding values one at a time
map(function, *iterables)
filter(function, iterable)
map
Calculate the squares of a sequence
#!/usr/bin/env python3
squares = map(lambda x: x ** 2, [1, 2, 3, 4, 5])
print(squares) # nothing was computed yet
print(list(squares))
filter
Filter odd numbers
#!/usr/bin/env python3
odd_numbers = filter(lambda x: x % 2, [1, 2, 3, 4, 5])
print(odd_numbers) # nothing was computed yet
print(list(odd_numbers))
functools.reduce(function, iterable[, initial])
all(iterable) -> bool
True
if bool(x)
is
True
for all values in the iterableTrue
if the iterable is emptymap
using a boolean valued
functionany(iterable) -> bool
True
if bool(x)
is
True
for any value in the iterableFalse
if the iterable is empty#!/usr/bin/env python3
import functools
product = functools.reduce(lambda x, y: x * y, [1, 2, 3, 4, 5])
print(product)
operator
module provides functions for Python's
operators
E.g. operator.mul
corresponds to
lambda x, y: x * y
#!/usr/bin/env python3
import functools
from operator import mul
product = functools.reduce(mul, [1, 2, 3, 4, 5])
print(product)
numbers = [1, 3, 17]
if all(map(lambda x: x % 2, numbers)):
print('only odd numbers')
numbers.append(2)
if not all(map(lambda x: x % 2, numbers)):
print('not just odd numbers')
from collections import namedtuple
class Result:
def __init__(self, name, grade):
self.name = name
self.grade = grade
results = [Result('Joe', 3), Result('Maggie', 2), Result('Josh', 1),
Result('Sue', 2)]
if not any(map(lambda r: r.grade == 5, results)):
print('All students passed.')
results.append(Result('Francis', 5))
if any(map(lambda r: r.grade == 5, results)):
print('At least one student failed.')
#!/usr/bin/env python3
squares = [x ** 2 for x in [1, 2, 3, 4, 5]] # ~map
print(squares)
odd_numbers = [x for x in [1, 2, 3, 4, 5] if x % 2] # ~filter
print(odd_numbers)
#!/usr/bin/env python3
"""
Simple dict comprehension exchanging the keys and values of a dict.
Assumes that the values are unique and hashable.
"""
d = {'Martin': 7, 'Sue': 5, 'Pat': 12, 'Chris': 4}
print(d)
d = {v: k for k, v in d.items()}
print(d)
Use parenthesis instead of square brackets
Unlike list comprehensions, values are computed 'on demand'
#!/usr/bin/env python3
squares = (x ** 2 for x in [1, 2, 3, 4, 5])
print(squares)
print(list(squares))
Functional programming emphasizes pure functions and avoids side effects
functools.partial(.)
)