Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: se: # YOUR ANSWER HERE An example usage would be >>> def sq(x): return x*x >>> test = Memo(sq) >>> test.val(2) 4 >>> test.val(3) 9 >>> test.val(3) found 3 in history 9 >>> test.val(8) 64 >>> test.val(5) 25 >>> test.history {8: 64, 2: 4, 3: 9, 5: 25} Midterm 2 Solutions — Spring 10 12 6.1 Complete the definition of this class, by supplying the code for the else part of the val method. Make sure that you do not execute the procedure more than once for any given argument. self.history[arg] = self.proc(arg) return self.history[arg] 6.2 The approach above works with any procedure of one argument that does not have side-effects. However, if we know that the procedure has some additional structure, we can be even more efficient. Assume we know that our procedure takes a single number as an argument and that the procedure is even, that is, proc(arg) == proc(-arg). Examples of even procedures are abs, math.cos and sq as defined above. Write a definition for the MemoEven class. Your solution must use inheritance, and ensure that there is a val method defined. Do not change the definition of Memo or repeat any of the code it contains. class MemoEven(Memo): def val(self, arg): return Memo.val(self, abs(arg)) Midterm 2 Solutions — Spring 10 13 7 Red vs Blue (12 points) Let’s build a voting tabulator for the national elections (except that we’re going to assume that there are only 4 states). The definitions below initialize the instance and allow us to enter votes, by state, for each candidate. We’re going to keep the votes data in the dictionary stateVotes. There is an entry in stateVotes for each state. The value stored for a state is itself a dictionary that stores the votes from that state for each candidate. A simple example, for two states (’MA’ and ’TX’) and two candidates, ’O’ and ’M’, would be: {’MA’: {’O’:100, ’M’:50}, ’TX’: {’O’:50, ’M’:100}} class Votes: def __init__(sel...
View Full Document

This document was uploaded on 03/17/2014 for the course ELECTRICAL 6.01SC at MIT.

Ask a homework question - tutors are online