Divide and Conquer
Chapter: Divide and Conquer
Suppose we want to have our turtle draw a sequence of num squares alternating
between two colors, like this:
Look at the code in this file to see how divide and conquer
makes for a really short and sweet solution.
num is the number of squares we want, len is the side length of
each square, gap is the number of pixels between each pair of adjacent
squares, and color1 and color2 are the two colors.
The key insights into how this problem was solved are:
- To draw num squares we simply
- draw one square (a very small problem)
- solve the slightly smaller problem of drawing num-1 squares
with the order of the colors reversed.
- The very small problem is solved directly with one line of code
- The slightly smaller problem is solved using recursion
- The glue is the moving into position that we do in between
calls and the reversal to make sure we end up where we started.
Write code to draw a sequence of num squares, the first of side len and succeeding squares each smaller than its predecessor by a factor
shrink separated by gap and alternating between three colors. For example, a call to triColorShrinkingSquares(10, 50, 5, .9, 'red', 'blue', 'green') results in:
Save your file as ex2sol.py
Notice that my code is invariant in that the turtle ends up where it
started. This makes it particularly easy to complete the next exercise.
You won't need to modify anything in your ex2sol.py except the lines that call
the functiontriColorShrinkingSquares. Save your code as ex3sol.py. Use calls to triColorShrinkingSquares and turtle turn commands to
draw this picture:
.
rpricejones@wooster.edu