Homework 4

The reading for this assignment is Chapter 4 of How to think....

Recurtle the Turtle

  1. On paper, sketch what you think this program will draw:

    def draw(t, dist, n):
        if n==0:
            return
        fd(t, dist)
        lt(t)
        draw(t, dist, n-1)
    
    bob = Turtle(world)
    draw(bob, 50, 4)
    

  2. Now type the code into turtle_code.py and run it using World.py. Did you get what you expected?

  3. Draw a stack diagram that shows the state of the program when n == 0.

  4. Now change draw so that if n is even, the turtle turns left, and if n is odd, it turns right. What do you expect to see? Run the code and check.

  5. From the department of deliberate errors, remove the lines that say

        if n==0:
            return
    
    Now the recursion has no base case, so it will keep going, calling draw over and over. If you wait long enough, eventually the stack grows too big and you'll get a RuntimeError: maximum recursion depth exceeded.

Mating Amoebas

In this section, we will investigate the mating behavior of amoebas. But remember, this isn't exactly biology[*].

  1. Download http://wb/ip/code/Amoebas.py. Read over the code and then run it. You should see two amoebas moving around the slide at random.

  2. Inside the move function, add code that keeps the amoebas from moving off the slide. Notice that move takes an optional parameter named limit that is meant to be the boundary. That is, the coordinates of the amoeba should always be between -limit and +limit.

  3. You might notice that the amoebas sometimes have trouble finding each other. It's like a microscopic version of a Jane Austen novel. But from our omniscient point of view, we can help them by changing the code that controls their behavior.

    Write a function called nudge that takes two amoebas as parameters and that tries to move the first amoeba toward the second amoeba by some small amount. Inside main, you can nudge each amoeba toward the other.

    Keep it simple: nudge doesn't have to do very much to get the amoebas together.

  4. Inside main and after both amoebas have moved, add code that computes the distance between the amoebas and, if it is less than 1.0, changes the behavior of the amoebas in a way that you think is appropriate.



... biology[*]
Google ``Sex and the single amoeba'' for more information (than you wanted).