csc108_final_2011f

16
NAME (PRINT): STUDENT #: __________ SIGNATURE: _______ UNIVERSITY OF TORONTO MISSISSAUGA DECEMBER 2011 FINAL EXAMINATION CSC108H5F Introduction to Computer Programming Andrew Petersen Duration - 3 hours Aids: None The University of Toronto Mississauga and you, as a student, share a commitment to academic integrity. You are reminded that you may be charged with an academic offence for possessing any unauthorized aids during the writing of an exam, including but not limited to any electronic devices with storage, such as cell phones, pagers, personal digital assistants (PDAs), iPods, and MP3 players. Unauthorized calculators and notes are also not permitted. Do not have any of these items in your possession in the area of your desk. Please tum the electronics off and put all unauthorized aids with your belongings at the front of the room before the examination begins. If any of these items are kept with you during the writing of your exam, you may be charged with an academic offence. A typical penalty may cause you to fail the course. Please note, you CANNOT petition to re-write an examination once the exam has. I: begun. - " 14"..," """_ MARKING GUIDE 1: / 3 This final examina.tion consists of 7 questions on 20 pages (including this one). When you # 2: / 3 receive the signal to start, make sure that your copy of the examination is complete. # 3: /14 4: / 5 If you need more space for one of your solutions, use the last pages of the exam and 5: / 7 indicate clearly the part of your work that should be marked. 6: 7 # 7: /11 TOTAL: /50 CONTINUED ON PAGE 2

Upload: examkiller

Post on 27-Dec-2015

25 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CSC108_Final_2011F

NAME (PRINT):

STUDENT #: __________ SIGNATURE: _______

UNIVERSITY OF TORONTO MISSISSAUGA DECEMBER 2011 FINAL EXAMINATION

CSC108H5F Introduction to Computer Programming

Andrew Petersen Duration - 3 hours

Aids: None

The University of Toronto Mississauga and you, as a student, share a commitment to academic integrity. You are reminded that you may be charged with an academic offence for possessing any unauthorized aids during the writing of an exam, including but not limited to any electronic devices with storage, such as cell phones, pagers, personal digital assistants (PDAs), iPods, and MP3 players. Unauthorized calculators and notes are also not permitted. Do not have any of these items in your possession in the area of your desk. Please tum the electronics off and put all unauthorized aids with your belongings at the front of the room before the examination begins. If any of these items are kept with you during the writing of your exam, you may be charged with an academic offence. A typical penalty may cause you to fail the course.

Please note, you CANNOT petition to re-write an examination once the exam has.I:

begun.

- " ~;:Z 14"..," """_

MARKING GUIDE

1: / 3This final examina.tion consists of 7 questions on 20 pages (including this one). When you # 2: / 3 receive the signal to start, make sure that your copy of the examination is complete. # 3: /14

4: / 5If you need more space for one of your solutions, use the last pages of the exam and 5: / 7 indicate clearly the part of your work that should be marked. 6: 7

# 7: /11

TOTAL: /50

CONTINUED ON PAGE 2

Page 2: CSC108_Final_2011F

- - -

CSCI08H5F FINAL EXAMINATION, DECEMBER 2011 Page 2 of 20

3 marks Question 1. Tracing: Strings and Lists

1 def mysteryl(sl. 52) :

2 L = [] 3 for ch in 51: 4 if ch in 52: 5 L. append (ch) count £) return L

8 def my5tery2(word): 9 count = e

19 for ch in word: Global variables: .. ". 11 if ch.lowerO -- ch:~

mystery1 function (id:l)12 count += 1 return count mystery2 function (id=2)

.. ...15 if name -- main s1-16 sl "Final exam" 17 52 ::: "Good luck!" . STR Cd"4):

s2 . rG~~d'i~~-k!-i L....... j

19 print PI:", mystery1(sl. 52)

2e ... prin t " 2 : " '"!l'~,~_~Q'2 f.lhl cqde

: «flrst:;:'Bilck. Step 52 of 69!3;Wa;:d~.

Program output:

1 mark Part (a) The figure above is a screenshot of the online visualizer that we used in lecture and in lab. At the point that the screenshot was taken, line 11 is just about to execute but has not yet executed. The value of count has been hidden. 'Vhat is its value?

2 marks Part (b) After this program completes, what will be displayed in the "Program output" box?

CONTINUED ON PAGE 3

Page 3: CSC108_Final_2011F

--

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 3 of 20

3 marks Question 2. Tracing: Dictionaries

The figure below is a screenshot of the online visualizer that we used in lecture and in lab. At the point that the screenshot was taken, line 15 (designated by an arrow) is just about to execute but has not yet executed. You can confirm this by seeing the lack of output in the "Program Output" box.

Several of the areas where object values are displayed have been replaced by empty boxes. Fill in each box with the value the visualizer displayed. There are nine boxes to fill in: three for each dictionary. (The object IDs have also been hidden, but you do not need to fill those values in.)

Glob,,1 variables:1 cef rnystery(dl, 02): 2 for key in a1: mystery function (id=l) 3 if key in d2: • dl[key] • d2[key) • 1 5 d2[key] ~ d2[key! ~ 1

7 if _!~ame_ "'''' "_rnai 0_" ,

B d '" {"a": e. "b"; 1. "C: 2}

9 d_copy = d.copy() 19 a_assign'" d

12 mystery(d. a_copy) 13 mystery(d. d_assign)

IS print d

«'.< '" Step 39 of 39 '

Program output:

CONTINUED ON PAGE 4

Page 4: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 4 of 20

14 marks Question 3. Short Answer: Mixed Topics

Each of the sub questions in this section contains a block of code. Handle each subquestion inde­pendently (subquestions are not related), and answer each in the space provided.

1 mark Part (a) Expressions

Write an expression that evaluates to True if and only if the list L contains no elements.

1 mark Part (b) Slicing

Assume that the variable s refers to a str object of length greater than 10. Use slicing to assign the characters in s at the indices 5 to 9 (inclusive) to the variable slice.

1 mark Part (c) Calling Functions and Casting

Call the raw_input function (with no prompt specified) to get an int from the user. Assign the integer to the variable value.

1 mark Part (d) Opening Files

Write a line of code that opens the file "output.txt" for writing and assigns the open file to the variable reader.

1 mar'k Part (e) Calling Methods

Assume that the variable L refers to a list with at least one item in it. Call a method to remove the first item in the list and to assign it to the variable first.

CONTINUED 01\ PAGE 5

Page 5: CSC108_Final_2011F

CSCI08H5F FINAL EXAMINATION, DECEMBER 2011 Page 5 of 20

1 mark Part (f) Removing Items

Assume that the variable L refers to a list. Remove all instances of the str "cat" from the list 1.

1 mark Part (g) Defining Functions

Define a function "is_odd" that takes a single int parameter and returns True if and only if the parameter is odd. You do not need to write a docstring for this function.

1 mark Part (h) Looping and Aliasing

Assume that the variable nested_list refers to a list of lists. Each of the internal lists contains int and str values. Write code to create a deep copy of nested_list and assign the copy to the variable copied_list. (In a deep copy, the internal values are also duplicated.)

1 mark Part (i) Conditionals in Loops

Assume that the variable strings refers to a list containing str objects. Write code that generates a list long_strings that contains only those strings in strings with length greater than 10.

CONTINUED ON PAGE 6

Page 6: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATIOK, DECEMBER 2011 Page 6 of 20

1 mark Part (j) Updating Dictionaries

Assume that the variable d refers to a dictionary in which every value is a str. Update d so that every value is in lowercase.

1 mark Part (k) Looping over Files

Assume that the variable reader refers to an open file. Print every line in the file that does not contain an "=" (equals sign).

~-----------------------------------------------------------------------~

1 mark Part (1) Constructors

Assume that the class Rainbow has been defined and has a constructor that takes no arguments. Create a Rainbow object and assign it to the variable roygbiv.

2 marks Part (m) Defining Classes

Assume that the class Star has been defined. Define a class RedGiant that inherits from Star. The new class should contain a method classification that takes no additional parameters and returns "Red Giant".

CONTINUED ON PAGE 7

Page 7: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 7 of 20

5 marks

1 mark

Question 4. Complexity

Part (a) What is the worst-case complexity of the following function?

#L is a list of length n. def list_func(L):

total = 0 for i in range(5) :

total += i return total

1 mark Part (b) What is the worst-case complexity of the following function?

#L is a list of length n. def list_func(L):

total = 0 for i in range(len(L)):

total += L[iJ return total

1 mark Part (c) What is the worst-case complexity of the following function?

#L is a list of length n. def list_func(L):

for i in range(len(L)): for j in range(i, len(L)

if L[j] > L[j + 1]: L[j], L[j + 1] =

- 1):

L[j + 1], L[j]

1 mark Part (d) In one sentence, provide justification for using bubblesort instead of the other sorts we investigated.

1 mark Part (e) In one sentence, provide justification for using mergesort instead of the other sorts we investigated.

CONTINUED ON PAGE 8

Page 8: CSC108_Final_2011F

CSCI08H5F FINAL EXAMINATION, DECEMBER 2011 Page 8 of 20

7 marks Question 5. Nested Lists

In assignment 2, you dealt with association lists. Recall that an association list is a list of lists where each sublist has two elements. The first element is called a "key" and is a value of any type, and the second is a list of values (of any type) that are associated with that key. No key occurs more than once in an association list. For example:

[[nail, [1,2, 3JJ, [lib", [2,3, 4JJ, ["C" , [7JJJ

:3 marks Part (a) Write the following function according to its docstring.

def get_values (alist, k): "'Return a copy of the list of values associated with the key k in the association list alist. If k is not a key in alist, return None.'"

CONTINUED ON PAGE 9

Page 9: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 9 of 20

4 marks Part (b) Since keys in an association list are unique, merging two association lists requires that the lists of values be merged if the same key is found in both lists. For example:

alistl = [["a", [1, 2, 3JJ, ["b", [2, 3, 4JJJ alist2 = [["b", [1, 5J], [lid", [1, 7J]J merged_alist = [[lIa ll , [1,2,3]]' [lib", [2,3,4,1,5]]' [lid", [1, 7]JJ

Write the following function according to its docstring. You may call the function from the previous subsection if it is helpful to do so. Do not be concerned about duplicates in the value listl:i.

def merge_alists(alist1, alist2): "'Return a new alist that contains all of the associations in the association lists alist1 and alist2. '"

CONTINUED ON PAGE 10

Page 10: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 10 of 20

7 marks Question 6. Files

3 marks Part (a) Assume that you have a set of files of the same format. Each file is made up of three pieces, in order: a header section, a division line, and a body section. The division line is a line with only equals signs (=) that is at least 10 characters long. The header section has at least one line, but the body section might be empty. Even if the body is empty, the division line is still there. No lines in the body or the header can have the same structure as a division line.

Write the following function according to its docstring.

def line_count(f): "'Return a tuple where the first element is the number of header lines in open file f and the second element is the number of body lines. f is a file in the format described above.'"

CONTINUED ON PACE 11

Page 11: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 11 of 20

4 marks Part (b) Assume that you have a file in which each line is a record in the following format:

month,day,year:high_temperature , low_temperature: amount_precipitation

Every field in each line can be cast to into Write the following function according to its doc­string.

def parse_weatherdata(f): "'Return a tuple where the first element is the highest temperature recorded in the open file f, the second element is the lowest temperature, and the third element is the total precipitation. Each element in the tuple is an integer. f is a file in the format described above.'"

CONTINUED ON PAGE 12

Page 12: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 12 of 20

11 marks Question 7. Dictionaries and Graphs

In assignment 3, you used actor and movie dictionaries to store the nodes and edges of a graph, In this question, we will use a single dictionary to store a graph representing cities and the roads that connect them, Each key in the dictionary is a str representing a city, and each key is associated with a list of strs representing the other cities connected to it by road, For example, the following dictionary represents a small road network where the city Aville is connected directly to Bville and Csauga: {"Aville": [IIBville", "Csauga"], "Bville": [IIAville"], "Csauga": ["Aville"],

"AlonevilleII : []}

In the example above, note that there is a path from Bville to Csauga, since you could drive from Bville to Aville and then from Aville to Csauga. Aloneville, however, is not connected to any of the other cities in the graph. In addition, any city that is not a key in the dictionary is assumed to not be connected to any other cities in the graph.

4 marks Part (a) Write the following function according to its docstring. Hint: Recall that iterating over a collection while removing items from it is hazardous.

def remove_cities(map_dict, city_list): "'Update the graph map_dict by removing all references to the cities in list city_list, The cities in city_list may appear as keys, in value lists, or both.'"

CONTINUED ON PAGE 13

Page 13: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 13 of 20

3 marks Part (b) Complete the table below by adding three distinct cases you would use to test the function described below. (Do not implement the function yet. You will do so in the next subquestion.) For each case, provide a specific value for map and for start_city as well as the expected output of the function.

All of the test cases should test something significantly different. You will receive no credit for repetitive test cases or test cases that check for invalid input.

def connected_cities (map, start_city): "'Return the list of all cities connected to the str start_city by a path of any length. map is a graph dict as described in the question header. A city is, by default, connected to itself. "l

Value of map Value of start_city vn<>{'tt'rl result

I

CONTINCED ON PAGE 14

Page 14: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 14 of 20

4 marks Part (c) Write the following function according to its docstring.

def connected_cities (map, start_city): "'Return the list of all cities connected to the str start_city by a path of any length. map is a graph dict as described in the question header. A city is, by default, connected to itself.'"

Total Marks = 50

CONTINUED ON PAGE 15

Page 15: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 19 of 20

Short Python function/method descriptions: __builtins__ :

abs(num) -) number Return the absolute value of the number num.

len (seq) -) int Return the number of items in the sequence seq. Lists and strings are sequences.

max(a, b, c, ... ) -) object With two or more arguments, return the largest argument.

min(a, b, c, ... ) -) object With two or more arguments, return the smallest argument.

open(name[, mode]) -) file object Open a file. Legal modes are "r" (read), "w" (write), and "a" (append).

range([start], stop, [step]) -) list of ints Return a list containing the integers starting with start and ending with stop - 1 with step specifying the amount to increment (or decrement). If start is not specified, the list starts at O. If step is not specified, the values are incremented by 1.

raw_input«(prompt]) -) string Read a string from standard input. The trailing newline is stripped. The str prompt, if given, is printed without a trailing newline before reading.

dict: del D [k]

Remove the key k (and its associated value) from D. D.copy() -) dict

Return a shallow copy of D. D.get(k) -> object

Return the value associated with the key k in D. D.has_key(k) -) bool

Return True if k is a key in D and False otherwise. D.keys() -) list of objects

Return the keys of D. D.values() -) list of objects

Return the values associated with the keys of D. D.items() -> list of (object, object) pairs

Return the (key, value) pairs of D, as 2-tuples. D.setdefault(k[,d]) -) object

Return the value associated with key k in D and set D[k] d if k not in D. file (also called a "reader"):

F .closeO Close the file.

F.read([size]) -) read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF (End of File) is reached.

F.readline([size]) -) next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF.

F.write(string) Write the string to the end of the open file.

float: float(x) -) float

Convert x to a float, if possible. int:

int(x) -) integer Convert x to an integer, if possible.

CONTINUED ON PAGE 20

Page 16: CSC108_Final_2011F

CSC108H5F FINAL EXAMINATION, DECEMBER 2011 Page 20 of 20

list: x in L --> bool

Return True if x is in L and False otherwise. L.append(x)

Append x to the end of the list L. L.count(obj) -> int

Returns the number of times obj occurs in L. L.extend(iter)

Append all elements in the iterable iter to L. L.index(obj) -> int

Returns the lowest index of obj in L. L.insert(index, x)

Insert x at position index in L. L.pop([index]) -> object

Remove and return the object at index (the last item, by default). L.remove(obj)

Removes the first occurrence of obj from L. L.sortO

Sorts the list in ascending order. str:

x in s --> bool Return True if x is in s and False otherwise.

S.find(sub[,start [,end]]) -> int Return the lowest index in S where the string sub is found or -1 if sub does not occur in S. Optional arguments start and end are interpreted as in slice notation and designate the range in which rfind operates.

S.index(sub) -> int Like find but raises an exception if str sub does not occur in S.

S.isdigit() -> boo I Return True if all characters in S are digits and False otherwise.

S.lower() -> str Return a copy of the string S converted to lowercase.

S.replace(old, new) -> str Return a copy of string S with all occurrences of the string old replaced with the string new.

S.rfind(sub[,start [,end]]) -> int Return the highest index in S where the string sub is found or -1 if sub does not occur in S. Optional arguments start and end are interpreted as in slice notation and designate the range in which rfind operates.

S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead.

S.split([sep]) -> list of strings Return a list of the words in S, using string sep as the separator and any whitespace string if sep is not specified.

S.strip([chars]) -> str Return a copy of S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead.

S.upper() -> str Return a copy of the string S converted to uppercase.

END OF EXAMINATION