Practice final exam answers
CS 121B, Spring 2014
def report(lis): desirable = 0 borderline = 0 high = 0 # invar: desirable, borderline, and high contain counts of the # readings in those ranges for all readings seen so far for chol in lis: if chol < 200: desirable = desirable + 1 elif chol < 240: borderline = borderline + 1 else: high = high + 1 total = desirable + borderline + high return "{:.1%} desirable, {:.1%} borderline, {:.1%} high".format( desirable/total, borderline/total, high/total)
def countInput(prompt): print(prompt) lines = 0 words = 0 chars = 0 # invar: lines, words, and chars hold the counts of lines, # words, and characters seen so far nextline = input() while nextline != '': lines = lines + 1 words = words + len(nextline.split()) chars = chars + len(nextline) + 1 nextline = input() print("Summary: {:d} words, {:d} characters".format(words,chars)) return lines
# iterative solution def replaceD(lis, sdict): retval = [] # invar: retval holds all words seen so far, after replacing words that # are keys in sdict with those keys' values, capitalized for word in lis: if word in sdict: retval = retval + [sdict[word].upper()] else: retval = retval + [word] return retval # recursive solution def replaceD(lis, sdict): if lis == []: return [] # assert: at least one element in lis elif lis[0] in sdict: return [sdict[lis[0]].upper()] + replaceD(lis[1:], sdict) # assert: first element is not a key in sdict else: return [lis[0]] + replaceD(lis[1:], sdict)
def nnn(lis): # any possibly nested list if lis == []: return [] elif type(lis[0]) == int or type(lis[0]) == float: return [-lis[0]] + nnn(lis[1:]) elif type(lis[0]) == list: return [nnn(lis[0])] + nnn(lis[1:]) else: return [lis[0]] + nnn(lis[1:])
Mapper:
# IN keys and values: # key: holds a line number, colon, then chapter name # value: a line of text # OUT keys and values: # key: a word from that text, in lower case # value: chapter name, space, line number for that word def mapper(key, value): lis = key.split(':') outval = lis[1] + ' ' + lis[0] for word in value.split(): Wmr.emit(word.lower(), outval)
Reducer:
# IN keys and values: # key: a word from that text, in lower case # value: chapter name, space, line number for that word # OUT keys and values: # key: holds a word from that text, in lower case # value: chapter name, space, line number, comma, and space for # each occurrence of that word in lines of input text def reducer(key, iter): accum = '' # invar: accum holds values seen so far, each followed by comma and space for val in iter: accum = accum + val + ', ' Wmr.emit(key, accum)
class Firm: '''Represents a business firm State variables: name -- String, name of this firm size -- non-negative integer, the number of employees in this firm.''' def __init__(self, name, size): self.name = name self.size = size def getName(self): return self.name def getSize(self): return self.size def setName(self, newname): prev = self.name self.name = newname return prev
class Corp(Firm): '''Represents an incorporated business firm State variables: id -- Integer, an id for this firm. nextId -- Integer, the lowest unused value for a firm {\tt id}, initially 1. (CLASS VARIABLE)''' nextId = 1 def __init__(self, name, size): Firm.__init__(self, name, size) self.id = Corp.nextId Corp.nextId = Corp.nextId + 1 def __str__(self): return "{:d}. {:s} ({:d} employees)".format( self.id, self.name, self.size)
Alternative implementation of __str__()
def __str__(self): return str(self.id) + '. ' + self.name + ' (' + \ str(self.size) + ' employees)'
import turtle win = turtle.Screen() tom = turtle.Turtle() tom.penup() tom.goto(25,60) tom.pendown() tom.right(90) tom.forward(20) tom.left(90) tom.forward(50) tom.left(90) tom.forward(20) tom.left(90) tom.color('red') tom.forward(50) tom.penup() tom.color('black') tom.goto(45,45) tom.pendown() tom.write("Tools")
def quarterGray(img): img2 = image.EmptyImage(img.getWidth(), img.getHeight()) for row in range(img.getHeight()): for col in range(img.getWidth()): pixel = img.getPixel(col, row) if row < img.getHeight()/2 and col < img.getWidth()/2: mean = int((pixel[0] + pixel[1] + pixel[2])/3) pixel = image.Pixel(mean,mean,mean) img2.setPixel(col, row, pixel) return img2
math.sqrt(7)
acct = Account(500)defines an
Account
object having as state variables
balance
and initBal
, both initialized at 500
acct = Account(500)for the
Account
example discussed in class.