Lec4 Functions Recursion
Lec4 Functions Recursion
ABSTRACTION,
FUNCTIONS
def is_even( i ):
"""
"""
print("hi”)
return i%2 == 0
is_even(3)
def is_even( i ):
"""
"""
print("hi”)
return i%2 == 0
return x x 3
x = 3
z = f( x ) call to f, before z
body evaluated
February 22, 2016 6.0001 LECTURE 6 15
VARIABLE SCOPE
formal parameter gets bound to the value of
actual parameter when function is called
new scope/frame/environment created when enter a function
scope is mapping of names to objects
return x x 3
x = 3
z = f( x ) z
February 22, 2016 6.0001 LECTURE 6 16
VARIABLE SCOPE
formal parameter gets bound to the value of
actual parameter when function is called
new scope/frame/environment created when enter a function
scope is mapping of names to objects
return x x 3
x = 3
z = f( x ) z
February 22, 2016 6.0001 LECTURE 6 17
VARIABLE SCOPE
formal parameter gets bound to the value of
actual parameter when function is called
new scope/frame/environment created when enter a function
scope is mapping of names to objects
Global scope
def f( x ):
f Some
x = x + 1
code
print('in f(x): x =', x)
return x x 3
x = 3
"""
"""
i%2 == 0
def func_a():
print('inside func_a’)
def func_b(y):
print('inside func_b’)
return y
def func_c(z):
print('inside func_c’)
return z()
print(func_a())
print(5 + func_b(2))
print(func_c(func_a))
February 22, 2016 6.0001 LECTURE 6 21
SCOPE EXAMPLE
inside a function, can access a variable defined outside
inside a function, cannot modify a variable defined
outside
def f(y): def g(y): def h(y):
x = 1 print(x) x = x + 1
x += 1 print(x + 1)
print(x) x = 5
x = 5 h(x)
x = 5 g(x) print(x)
f(x) print(x)
print(x)
return x
z
x = 3
z = g(x)
z
x = 3
z = g(x)
z
x = 3
z = g(x)
z
x = 3
z = g(x)
None
z
x = 3
z = g(x)
return x
z 4
x = 3
z = g(x)
printName(‘Eric’, ‘Grimson’)
printName(‘Eric’, ‘Grimson’, True)
is_even(3)
EXAMPLE print(fact(4))
Global scope fact scope fact scope fact scope fact scope
(call w/ n=4) (call w/ n=3) (call w/ n=2) (call w/ n=1)
fact Some n n n n
4 3 2 1
code
By André Karwath aka Aka (Own work) [CC BY-SA 2.5 (http://creativecommons.org/licenses/by-sa/2.5)], via Wikimedia
Commons
February 22, 2016 6.0001 LECTURE 6 53
TOWERS OF HANOI
Having seen a set of examples of different sized stacks,
how would you write a program to print out the right
set of moves?
Think recursively!
• Solve a smaller problem
• Solve a basic problem
• Solve a smaller problem