Created by Alexander Hernandez / @pori_alex
Join us at sropythonusers@umich.edu
Programming that changes state to complete a task.
a = 0
b = 0
a += 160 # 160
a /= 5 # 4
def do_something(n):
b = a + n
do_something(10)
print b # 42
Describing what a program is rather than how it works.
a = 0
b = a + 160 # 160
c = b / 5 # 4
def do_something(a, b):
return a + b
d = do_something(c, 10)
print d # 42
A shorthand for functions.
# lambda x, y, ...: expression sgn = lambda x: -1 if (x < 0) else 1 if (x > 0) else 0 sgn(-5) # -1 sgn(5) # 1 sgn(0) # 0
Functions that take other functions as arguments, return functions, or both.
The most famous ones are map(), reduce(), filter().
list = [1, 2, 3, 4, 5]
def square(x):
return x*x
squared = map(square, list) # [1, 4, 9, 16, 25]
gt5 = filter(lambda x: x > 5, squared) # [9, 16, 25]
sum = reduce(lambda x, y: x + 7, gt5) # 23
Functions that take input and produce an output. The same input will always produce the same output, lacking side effects.
square = lambda x: x**2
As opposed to:
power = 2 square = lambda x: x**power print square(2) # 4 power = 0 print square(2) # 1
Syntax that sounds like what it's doing.
i.e.
SELECT * FROM superheroes WHERE city LIKE 'Metropolis';
In Python, this could be:
select('superheroes', where({ 'city': 'Metropolis' }))
Here's a mathematical definition:
An imperative implementation:
def fib(n): a, b = 0, 1 for i in range(0, n): a, b = b, a + b return a
Now let's try this Functionally:
def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2)
An imperative implementation:
import csv
def csvtodict (csvFile, delim):
headers = None
content = {}
reader = csv.reader(open(csvFile), delimiter=delim)
i = 1
for row in reader:
if reader.line_num == 1:
headers = row[0:]
else:
content[i] = dict(zip(headers, row[0:]))
i = i + 1
return content
incsv = r"path\to\file"
d_csv = csvtodict(incsv, ',')
print len(d_csv)
A functional implementation:
import csv load_csv = lambda f, delim: csv.reader(open(f), delimiter=delim) def csvtodict (csvFile, delim): reader = load_csv(csvFile, delim) headers = headers.next() content = map(lambda row: zip(headers, row), reader) return content incsv = r"path\to\file" csv_default_delim = lambda f: csvdict(f, ',') d_csv = csv_default_delim(incsv) print len(d_csv)
Any questions?
Don't forget to join us at sropythonusers@umich.edu