COMP 200: Elements of Computer Science
Spring 2013

Practice with Mutation and Loops

As always, work with your neighbor and talk about the problems. Also, upload your answers.

Mutation Toy Examples

Quiz 5 had several problems checking whether you understood mutation on lists. Here are a few more, some of which are trickier. What does each print? Try to figure each out before running it in CodeSkulptor.

Loops

Deleting elements of a list

In the previous example, one approach to implement noduplicates() would be to remove elements from the input list. In general, this is a common goal. For example, in a video game we might have a list of enemy ships, and we want to remove those that we've shot.

Collatz Conjecture

Back on Quiz 4, question 4 asked you to write a program for the Collatz Conjecture. The problem was pretty tough, especially given that loops had just been introduced. You've now had more practice with loops, so if you couldn't solve it then, try again now.

For your assignment

Here is an implementation of the predator-prey algorithm, in case you were unable to finish it in the previous class.

import simpleplot

def delta_h(h, l, hare_birth, hare_predation):
    """Returns the predicted annual change in hare population."""
    return h * hare_birth - h * l * hare_predation

def delta_l(h, l, lynx_birth, lynx_death):
    """Returns the predicted annual change in lynx population."""
    return h * l * lynx_birth - l * lynx_death

def populations(h, l, hare_birth, hare_predation, lynx_birth, lynx_death, years):
    """Returns the predicted populations of hare and lynx for the given inputs."""
    hare_pop = [(0, h)]
    lynx_pop = [(0, l)]

    for y in range(1, years + 1):
        h, l = (h + delta_h(h, l, hare_birth, hare_predation),
                l + delta_l(h, l, lynx_birth, lynx_death))

        hare_pop.append((y, h))
        lynx_pop.append((y, l))

    simpleplot.plot_lines("Hares and Lynx Populations", 600, 400,
                          "Years", "Population", [hare_pop, lynx_pop],
                          False, ["Hares", "Lynx"])

populations(100, 50, .4, .003, .004, .2, 50)

As you are working on assignment 2, there is one mysterious behavior you might encounter, and you would want to know why. As you try inputs for the predator-prey populations problem, your program might get very slow and even timeout. It is possible that the populations can get very big, and unfortunately CodeSkulptor's math is very slow with really big numbers. There's nothing you can do about it, except to use different inputs which don't lead to really big populations.