In [ ]:
images = ['./gifs/1.gif',....]
def convertClickToIndex(p):
if p.getX() < ....:
return 0
elif...
return 1
def getNeighbors(index):
if index == 0:
return [1,5]
elif...
%
//
In [ ]:
FUNCTIONAL PROGRAMMING IN PYTHON¶
Programming using ONLY expressions NO mutation of data NO loop statements NO if-else statements NO...
In [ ]:
# mutability of data
xs = [10,20,30]
xs.append(40)
print(xs)
[10, 20, 30, 40]
In [7]:
# immutability
# statement vs expression
y = 20
x = 2*y
# Conditional Expression
num = 21
x = 10 if num%2 == 0 else 0
# it is possible to nest conditional expressions!!
x = 50 * (10 if num%3 == 0 else 20 if num%3 == 1 else 30)
#if num%2 == 0:
# x = 10
#else:
# x = 0
print(x)
500
In [ ]:
# list/set/dictionary/tuple-comprehensions are types of expressions
# ways to create new lists/sets/dictionaries/tuples
xs = [i for i in range(10)]
#xs = []
#for i in range(10):
# xs.append(i)
print(xs)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [11]:
type((x for x in range(10)))
Out[11]:
generator
In [13]:
xs = [i+j for i in range(5) for j in range(5)]
print(xs)
[0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8]
In [14]:
xs = [i+j for j in range(5) for i in range(5)]
print(xs)
[0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8]
In [16]:
xs = [(i,j) for i in range(3) for j in range(3)]
print(xs)
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
In [17]:
xs = [(i,j) for i in range(3) for j in range(i)]
print(xs)
[(1, 0), (2, 0), (2, 1)]
In [18]:
# set comprehension
ss = {x for x in range(10) if x%2==0}
print(ss)
{0, 2, 4, 6, 8}
In [19]:
ds = {name:len(name) for name in ["John","Alice","Bob"] }
print(ds)
{'John': 4, 'Alice': 5, 'Bob': 3}
In [ ]:
# lambdas, map, filter, reduce
# to use reduce we must use the functools library (reduce is part of functools)
In [26]:
# lambdas are unnamed functions
def square(n):
return n*n
f1 = lambda n: n*n
# My name is Ihavenoname - Who's on First? skit from the 1930s
print(square(5), f1(5))
def add(x,y):
return x+y
f2 = lambda x,y: x+y
print(add(5,6), f2(5,6))
num = 22
#if num%2 == 0:
# z = f1(num)
#else:
# z = f2(num,num)
z = (lambda n: n*n)(num) if num%2 == 0 else (lambda x,y: x+y)(num,num)
print(z)
25 25 11 11 484