Reading: Percolation handout and Punch and Enbody Chapter 16
Average: 83
Median: 85
Standard Dev: 11.2
High Score: 93
Read the linked handout above. The slides from lecture are also provided on Courseworks but all you really need is percolation_handout.pdf document linked to above. We will use numpy arrays to help us model percolation.
Example: n factorial Suppose we wish to write a function to compute n factorial in Python. Given what we know now we might right something like this.
def f(n):
product=1
for p in range(1,n+1):
product = product*p
return product
Now a different approach
def f(n):
if n<=1:
return 1
else:
return n*f(n-1)
What just happened? The new approach uses recursion. A recursive function is a funtion that calls itself as part of its execution. What?? How is that even possible?? The way to understand recursion your first time seeing it is to just get stupid. Just follow instructions. The function above calls itself, so what? Just execute one instruction after another. Trace the code above with n = 3 and notice that the world doesn't come to an end just because the function calls itself. What makes this a feasible solution method is two things:
More formally there are three necessary qualities that a problem should have before we consider a recursive approach.
Example: string reversal
Consider the problem of reversing the order of the characters in a string. For example, given the string
s = 'abcd'
we would like to construct a function reverse such that
reverse(s)='dcba'
Is this a suitable candidate for a recursive solution? What would be the base case? A natural way to guage the size of a string reversal instance is the length of the string, right? So the smallest case would be a string of length 1. Reversing a string like this is trivial, we just leave it alone. We've just found our base case! Next we need to figure out how to formulate a bigger problem instance in terms of smaller instances. A good way to think about recursion is to imagine you have the function already. That is, suppose we have a magic function called reverse already. Then observe that reversing the string 'abc' may be solved in terms of a smaller solution as
'c' + reverse('ab')
more generally we can write:
reverse(s) = s[-1] + reverse(s[:-1])
Together with our base case we get:
def reverse(s):
if len(s)<=1:
return s
else:
return s[-1]+reverse(s[:-1])
reverse('abcd')
Recursion takes some getting used to but it's a powerful and widely used solution method. It's not always a win, but it's often worth investigating and will become much more natural over time. We will adopt a recursive approach for solving the more general undirected percoaltion problem. More on this next time.