Nov 19
Any questions about anything?
recursion
This week's assignment is from chapter 13, on algorithms & recursion.
We started talking about recursion on Tuesday - today we'll continue the discussion.
(This material is actually bit of a preview of some ideas we do in more depth in the Algorithms course.)
Definition:
Recursion: see "Recursion".
def print_it(x):
print x
def looper(i, stop_value, function):
if i <= stop_value:
function(i)
looper(i+1, stop_value, function)
looper(100, 110, print_it)
What does it do? And how is it doing it?
It turns out that this is an extremely powerful
technique, very similar to mathematical induction.
Consider a data structure that looks like this:
root = {'name' : 'root',
'parent' : []
}
branch = {'name' : 'branch',
'parent' : [root]
}
We can build trees and/or graphs by having
things like this that refer to each other.
(Another sort of recursion, actually ... not with functions, but
by embedding references within a data structure.)
In class, finish what we started on Tuesday :
- Make a python class that has some sort of "tree" structure.
- Create a tree.
- Write a recursive function which counts how many nodes are in the tree.
Perhaps we could write something that displays the tree for a game ... like the
subtraction game, which is
Nim with one pile.
There are more examples in the
recursion folder, including
searching a list, finding the max in a list, and a
complete computer player engine for the subtraction game.
The idea behind computer game search is this :
- Well, if we can win on this move, do that.
- Otherwise, take the best move of the positions we can reach. (Recursion!)
art
This site isn't python,
but is a nice collection of images defined with recursion.
Something along these lines could be accomplished
with Zelle's graphic library as a possible final project.
In class we wrote max_recur.py , attached.