Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

CS 1110 Prelim 2 Exam, Lecture notes of Introduction to Computing

This is a 90-minute exam for CS 1110 with 5 questions worth a total of 100 points. The exam covers Python string, list, and dictionary functions and methods, classes and subclasses, name resolution, and recursion. Students are expected to write Python code and follow the Academic Integrity Code.

What you will learn

  • How to implement the deblank and invert functions using for-loops?
  • What are the missing parts in the Pet and ExoticPet classes?
  • How to implement the ancestors and list2person functions using recursion?

Typology: Lecture notes

2021/2022

Uploaded on 09/27/2022

riciard
riciard 🇬🇧

4.4

(7)

234 documents

1 / 10

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Last Name: First: Netid: Section
CS 1110 Prelim 2 November 10th, 2016
This 90-minute exam has 5 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
You should not use while-loops on this exam. Beyond that, you may use any Python feature that
you have learned about in class (if-statements, try-except, lists, for-loops, recursion and so on).
Question Points Score
1 2
2 30
3 26
4 20
5 22
Total: 100
The Important First Question:
1. [2 points] Write your last name, first name, netid, and lab section at the top of each page. If
you cannot remember the section number, please write down your lab’s time and place.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download CS 1110 Prelim 2 Exam and more Lecture notes Introduction to Computing in PDF only on Docsity!

CS 1110 Prelim 2 November 10th, 2016

This 90-minute exam has 5 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

You should not use while-loops on this exam. Beyond that, you may use any Python feature that you have learned about in class (if-statements, try-except, lists, for-loops, recursion and so on).

Question Points Score

Total: 100

The Important First Question:

  1. [2 points] Write your last name, first name, netid, and lab section at the top of each page. If you cannot remember the section number, please write down your lab’s time and place.

String Functions and Methods

Function/Method Description

len(s) Returns: Number of characters in s; it can be 0. 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.replace(a,b) Returns: A copy of s where all instances of a are replaced with b.

List Functions and Methods Function/Method 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.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). x.sort() Rearrages the elements of x to be in ascending order.

Dictionary Functions and Methods

Function/Method Description

len(d) Returns: Number of keys in dictionary d; it can be 0. y in d Returns: True if y is a key d; False otherwise. d.keys() Returns: List containing all the keys in d. d.values() Returns: List containing all the values in d. It may have duplicates.

  1. [30 points] Classes and Subclasses

The next two pages have skeletons of two classes: Pet and ExoticPet. ExoticPet is a subclass of Pet, while Pet is only a subclass of object. You are to

  1. Fill in the missing information in each class header.
  2. Add getters and setters as approporiate for the instance attributes
  3. Fill in the parameters of each method (beyond the getters and setters).
  4. Implement each method according to its specification.
  5. Enforce any preconditions in these methods using asserts

Pay close attention specifications. There are no parameters beyond the ones specified. If a parameter has a default value, it is listed in the specification. There are no headers for getters or setters. You are to write those from scratch. However, you are not expected to write specifications for the getters and setters. Important: ExoticPet must not access the hidden attributes of Pet directly. If you need to access a hidden attribute, use methods from Pet.

Class Pet (CONTINUED).

def str( ): # Fill in parameters """Returns: A string representation of this pet. The string is the pet name with the license number in parentheses. A pet with a tag of -1 is "unclaimed". Examples: 'Sparky (pet #43)' or 'Rover (unclaimed)'"""

class ExoticPet( ): # Fill in missing part """Instances represent a pet certified by a wild-life official. IMMUTABLE ATTIBUTE (In addition to those from Pet): _official : The official that certified the pet [nonempty string] In addition, this class disables the setter setTag in Pets (you cannot change the license of an exotic pet). It does this by overriding setTag so that it creates a NotImplementedError (an an class built into Python) whenever it is called."""

PUT GETTERS/SETTERS HERE AS APPROPRIATE. SPECIFICATIONS NOT NECESSARY.

OVERRIDE THE SETTER FOR TAG, BUT NOT THE GETTER.

Class ExoticPet (CONTINUED).

def init( ): # Fill in parameters """"Initializer: Creates an exotic pet with name, tag, and official. In the case of an exotic pet, the tag is not optional and must be a value greater than -1. Precondition: Parameter name is a nonempty string Precondition: Parameter tag is an int >= 0 Precondition: Parameter official is a nonempty string"""

def str( ): # Fill in parameters """Returns: A string representation of this exotic pet The string is the same as for Pet, except that it also includes the official who certified the pet. Example: 'Tigger (pet #675); authorized by Sgt. O'Malley'"""

  1. [26 points total] Folders and Name Resolution

Consider the two (undocumented) classes below, together with their line numbers.

1 class A(object): 2 z = 5 3 4 def init(self,x): 5 self.x = x+self.z 6 7 def up(self): 8 shift = self.x-self.z 9 return B(shift,shift) 10

11 class B(A): 12 z = 10 13 14 def init(self,x,y): 15 A.init(self,x) 16 self.y = y 17 18 def down(self): 19 shift = self.x-self.z 20 return A(shift)

Call Frames Global Space Heap Space

3

4

5

6

7

  1. [20 points total] Iteration.

The following functions take (possibly empty) strings as their input. Use for-loops to implement them according to their specification. You do not need to enforce the preconditions. (a) [8 points] In class, we saw how to implement the function below with recursion. This time do not use recursion; use a for-loop instead. def deblank(s): """Returns: A copy of the string s with spaces removed Example: deblank('a b cd') is 'abcd' Precondition: Parameter s is a (possibly empty) string"""

(b) [12 points] An inverted string is a dictionary whose keys are characters and whose values are lists of positions. For example, the string 'hello' is inverted as the dictionary { 'h':[0], 'e':[1], 'l':[2,3], 'o':[4] } You are free to use anything about lists or dictionaries to create an inverted string. def invert(s): """Returns: An inverted string representing s Example: invert('abcac') is {'a':[0,3], 'b':[1], 'c':[2,4]}. invert('') is {}. Precondition: Parameter s is a (possibly empty) string"""

(b) [11 points] As we have seen, making a Person is a complicated affair. You have to create each ancestor object individually. One way to create Person objects quickly is to use a geneaology list. A geneaology list is defined recursively as follows:

  • It is a nonempty list with exactly three elements.
  • The first element is a nonempty string, respresenting the person’s name.
  • The last two elements are either None or genealogy lists. Looking at the Person objects on the previous page, s is ['Jane',None,None] while q is ['Robin',['Jane',None,None],None]. We can even represent p as the list ['Jack',['Robin',['Jane',None,None],None], ['John',['Ellen',None,None],['John',None,None]]] Use this recursive definition to implement the function below.

Hint: This problem is actually very simple. Just read the definition above.

def list2person(glist): """Return: A person object equivalent to the given genealogy list. Example: list2person(['Fred', None, None]) is Person('Fred',None,None) See the description above for more examples. Precondition: glist is a genealogy list."""