






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







This 150-minute exam has 8 questions worth a total of 100 points. Scan the whole test before starting. Budget your time wisely. Use the back of the pages if you need more space. You may tear the pages apart; we have a stapler at the front of the room.
It is a violation of the Academic Integrity Code to look at any exam other than your own, look at any reference material, or otherwise give or receive unauthorized help.
You will be expected to write Python code on this exam. We recommend that you draw vertical lines to make your indentation clear, as follows:
def foo(): if something: do something do more things do something last
Unless you are explicitly directed otherwise, you may use anything you have learned in this course.
You may use the backside of each page for extra room for your answers. However, if you do this, please indicate clearly on the page of the associated problem.
The Important First Question:
String Operations
Expression Description
len(s) Returns: Number of characters in s; it can be 0. a in s Returns: True if the substring a is in s; False otherwise. s.find(s1) Returns: Index of FIRST occurrence of s1 in s (-1 if s1 is not in s). s.count(s1) Returns: Number of (non-overlapping) occurrences of s1 in s. s.islower() Returns: True if s is has at least one letter and all letters are lower case; it returns False otherwise (e.g. 'a123' is True but ' 123 ' is False). s.isupper() Returns: True if s is has at least one letter and all letters are upper case; it returns False otherwise (e.g. 'A123' is True but ' 123 ' is False). s.lower() Returns: A copy of s but with all letters converted to lower case (so 'A1b' becomes 'a1b'). s.upper() Returns: A copy of s but with all letters converted to upper case (so 'A1b' becomes 'A1B'). s.isalpha() Returns: True if s is not empty and its elements are all letters; it returns False otherwise. s.isdigit() Returns: True if s is not empty and its elements are all numbers; it returns False otherwise. s.isalnum() Returns: True if s is not empty and its elements are all letters or numbers; it returns False otherwise.
List Operations
Expression Description
len(x) Returns: Number of elements in list x; it can be 0. y in x Returns: True if y is in list x; False otherwise. x.index(y) Returns: Index of FIRST occurrence of y in x (error if y is not in x). x.count(y) Returns: the number of times y appears in list x. x.append(y) Adds y to the end of list x. x.insert(i,y) Inserts y at position i in x. Elements after i are shifted to the right. x.remove(y) Removes first item from the list equal to y. (error if y is not in x).
Dictionary Operations
Expression (^) Description
len(d) Returns: number of keys in dictionary d; it can be 0. y in d Returns: True if y is a key in dictionary d; False otherwise. d[k] = v Assigns value v to the key k in dictionary d. del d[k] Deletes the key k (and its value) from the dictionary d. d.clear() Removes all keys (and values) from the dictionary d.
(b) [6 points] You have used the function int before. This function produces a ValueError if it cannot convert a string to an int (e.g. int('a')). In addition, it cannot convert a string with more than 4300 digits. In that case, assume it produces an OverflowError (which is not a subclass of ValueError). Using this knowledge, implement the function below. You must enforce the precondition with the error specified. def nextint(s): """Returns the string representation of next int after string s
If s does not represent an int, this function returns None. If it represents an int but has too many digits, this function returns the string 'inf'. Ex: nextint(' 10 ') returns ' 11 ', while nextint('a') returns None.
Precond: s is a string; this func causes a TypeError if it is not."""
if type(s) != str: raise TypeError()
try: n = int(s) n = n+ return str(n) except ValueError: return None except OverflowError: return 'inf'
The very first step in Assignment 7 was to make a welcome message with the class GLabel. As you may recall, it has the following following primary attributes.
Attribute Invariant Description x float x-coordinate of the label center. y float y-coordinate of the label center. text str The text to display. linecolor a color value (see below) The color for the text. fillcolor a color value (see below) The background color.
There are other attributes, such as width and height, but they are not important for this question. In particular, width and height are computed automatically from the text. GLabel is often the superclass of more interesting classes. In this problem, you are to make a GButton, which provides a clickable button. We are not going to add mouse support, but we will add an attribute indicating whether or not it is pressed. We want the button to change color when we press it. The simplest way to do this is to change the fillcolor to another value when it is pressed. This is shown to the right (the black button turns blue).
Implement this class below and on the next page. We have provided you with the specifications for the methods init and draw. You should fill in the missing details to meet these specifications. In addition, you must add the getters and setters (where appropriate) for the new attributes. You are not allowed to add any attributes beyond those in the class invariant. In addition, you should use isinstance instead of type when appropriate.
As part of this problem, you know that there are multiple ways to represent colors in Python (as strings, RGB objects, tuples, etc.). You can assume that you have the following function (do not implement this function).
def iscolor(value): """Returns True if value represents a valid GUI color """Precond: value can be anything"""
from game2d import *
class GButton(GLabel): """A class representing a clickable button."""
def setPressed(self,value): """Sets whether the button is pressed
Precond: value is a bool""" assert isinstance(value, bool) self._pressed = value
def getPressed(self): """Returns whether the button is pressed""" return self._pressed
def setVisible(self,value): """Sets whether the button is visible
Precond: value is a bool""" assert isinstance(value, bool) self._visible = value
def getVisible(self): """Returns whether the button is visible""" return self._visible
def getDownColor(self): """Returns the button color when pressed""" return self._downcolor
Implement the function below according to its specification. You do not need to enforce the precondition. def rowfold(table): """Returns a new table whose rows are the sums of the rows in table.
Each row in the new table is the sum of all rows up to AND INCLUDING that row in the original table.
Examples: rowfold([[1],[2],[3],[4]]) returns [[1],[3],[6],[10]] rowfold([[1,2],[3,4],[5,6]]) returns [[1,2],[4,6],[9,12]] rowfold([[1,2,3],[4,5,6]]) returns [[1,2,3],[5,7,9]] rowfold([[1,2,3]]) returns [[1,2,3]]
Precondition: table is a non-empty rectangular 2D list of integers"""
result = []
firstrow = table[0][:] result.append(firstrow)
for r in range(1,len(table)): row = [] for c in range(len(table[0])): value = table[r][c]+result[r-1][c] row.append(value) result.append(row)
return result
If you have ever downloaded DLC for a game, or redeemed a coupon online, you know that they are often defined as groups letters and numbers separated by dashes. The simplest variation has just one dash and groups its letters in numbers in blocks of four, like this: K97J-FTRE. The function below takes a string of (potentially lower case) letters and numbers and returns it as a string of (upper case) letters and numbers separateds into groups of 4. If the length of the string is not divisible by 4, the leftovers at the end are dropped. Implement this function using recursion. You do not need to enforce the precondition. An- swers using loops will receive no credit. def couponify(code): """Returns code properly formatted as a coupon code in blocks of 4.
Each block of a coupon code is composed of upper case letters and numbers. Dashes are used to separate the blocks from each other.
Example: couponify('k97J') returns 'K97J' couponify('K97j9876') returns 'K97J-9876' couponify('K97JfTRe9876') returns 'K97J-FTRE-9876' couponify('K97') returns '' couponify('K97J8') returns 'K97J' couponify('k97JfTRe9') returns 'K97J-FTRE'
Preconditions: code is a (possibly empty) string of letters and numbers"""
if len(code) < 4: return '' # Drop anything too small elif len(code) == 4: return code.upper() # Convert lower case letters
left = code[:4] left = left.upper() # Convert lower case letters right = couponify(code[4:])
if len(right) > 0: return left+'-'+right else: return left
1
2
3
4
5
A.f self id
8
Call Stack Global Space The Heap
a id
id B y 6 z 5
a id
id B y 6 z 5
A.f self id
11
id
B.g self id
26 y 0
A.f self id
8
A.f self id
11
A.f self id
11
B.g self id
25 y 0
A.f self id
11
B.g self id
26 y 0
a id
id B y 6 z 5
a id
id B y 6 z 5 x 0
a id
id B y 6 z 5 x 0
Call Stack Global Space The Heap 6
7
8
9
10
A.f self id
11
id
B.g self id
26 y 0
self id
9
A.f self id
11
id
B.g self id
26 y 0
A.f self id
A.f self id
11
id A.f self id RETURN^6
A.f self id RETURN^18
id
B.g self id1 y 0 RETURN^18
A.f self id RETURN^18
a id
id B y 6 z 5 x 0
b 18
RETURN 6
a id
id B y 6 z 5 x 0
a id
id B y 6 z 5 x 0
a id
id B y 6 z 5 x 0
a id
id B y 6 z 5 x 0
A.f
B.g self id1 y 0 RETURN^18