Summer.2008 - (6‘ UNIVERSITY OF TORONTO O 4‘96 Faculty...

Info iconThis preview shows pages 1–20. Sign up to view the full content.

View Full Document Right Arrow Icon
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 4
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 6
Background image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 8
Background image of page 9

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 10
Background image of page 11

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 12
Background image of page 13

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 14
Background image of page 15

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 16
Background image of page 17

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 18
Background image of page 19

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 20
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: (6‘ UNIVERSITY OF TORONTO O 4‘96 Faculty of Arts and Science 6'4 - AUGUST EXAMINATIONS 2008 $0 csc 108H1Y v.9 Instructor: Nowak Q’ ’t Duration — 3 hours Examination Aids: None Student Number: I l 1 Last (Family) Name(s): First (Given) Name(s): Do not turn this page until you have received the signal to start. (In the meantime, please fill out the identification section above, and read the instructions below carefully.) MARKING GUIDE This final examination consists of 9 questions on 20 pages (including this one). When you receive the signal to start, please make sure that your copy of the examination is complete. # 1' —/ 10 # 2: 8 Comments and docstrings are not required except where indicated, / although they may help us mark your answers. They may also get # 3: / 8 you part marks if you can’t figure out how to write the code. # 4: _/ 10 You do not need to put import statements in your answers. # 5: __/ 20 You may not use break or continue on this exam. # 6; _/ 8 If you use any space for rough work, indicate clearly what you want # 7: —/ 20 marked. # 8: _/ 11 Assume all input is valid unless otherwise indicated; there is no need # 9; _/ 10 to error—check. TOTAL: _/ 105 Good Luck! Page 1 CONT’D. .. 080 1081-118 FINAL EXAMINATION h I u, Question 1. [10 MARKS] Suppose that you have a Python file called extract .py with the following functions: def extract_numbers (str) : ” ’Given a string str, extract all numbers from str, returning them in a string. ’ ” def extract_letters (str) : ”’Given a string str, extract all alphabetic characters from str, returning them in a string. ’ ” Complete the program so that it reads from the keyboard lines in the form “string option” where string is a string and option is either “a” or “1” and extract all the letters or numbers respectively. The program will then print the resulting string. If option is not “a” or “1”, it should print “Error”. Write your program so that it is possible to import this module into another Python program so that it loads only the function definitions, and doesn’t run the code you are about to write. For example if the following lines are typed in: ab1c23 a t3 ab2 1 hello x the output (ignoring issues of number of significant digits) will be abc 32 Error Page 2 of 20 CONT’D. .. FINAL EXAMINATION CSC 108H18 Question 2. [8 MARKS] In the table below, trace the variable values during execution of mystery( ‘ 1425547’ ). For each blank in the table, fill in the specified variable’s value after the corresponding line has executed. Write “not reached” if that line was not executed. You do not need to complete the section of the table labeled ‘...’. You only need to complete the section for the last iteration if the loop iterates .3 or more times. In the last line, write the value returned by this function call. The last iteration is the last time that the body of the loop is entered. In the case of the mystery function below, it is the last time that the if statement is executed. Show variable values after each line has executed: def mystery(a) : i = 0 j = len(a) - 1 7 uring 2nd iteration t During 1st iteration fi' E? H'@ E...“ E|"|| “U c E. w on at g: (A Lit? a CF m H 81 H o u 93 . ,— H. while i < j: I am: if a[i] == a[j] a[i]: afi]: a[1] ab] - q = macaw __- q- r = int<ati+1=ji> I s = mam-Hm _I t = q + r + s I t: J- s I j: —_I i 2 I i: J 2 . i: return a value returned: Page 3 of 20 CONT’D. .. CSC 108H18 FINAL EXAMINATION 1.. ‘ Question 3. [8 MARKS] Write docstrings for the following functions. Include assumptions about the parameter values. Part (a) [4 MARKS] def mystery (L) : ))} 2)} c = 1 for i in range(len(L)): a = L[i] [03 b = L[i] [1] c *= (a / float(b)) return c Here is an example of a call: mystery( [(2, 1), (1, 5) , (3, 4)]). Part (b) [4 MARKS] def enigma(d): )2, ’77 e = {l for k in d: if (k in d.values()): eldlkll = k return e Hereis an exampleofacall: enigma({’b’:’a’, ’c’:’b’, ’d’:’e’}). Page 4 of 20 CONT’D, .. f' I . , FINAL EXAMINATION CSC 108E118 Question 4. [10 MARKS] Part (a) [6 MARKS] Complete the following function: def upper_letters(s, letters): ” ’Return a string that contains the characters in s but with the characters from the string letters made uppercase.’ ’ ’ Part (b) [4 MARKS] Fill in the rest of the table of test inputs and expected results below. We have filled in the first two rows, indicating that a call to upper_1etters(”, ’a’) should return an empty string, and the cal upper_letters(’a’ , ’a’) should return the string ’A’. Make sure that the test inputs you are proposing are different from each other. Also, don’t test error cases; for example, don’t provide invalid input such as an int instead of the expected string. s Expected result empty string case Page 5 of 20 CONT’D. .. CSC 108HIS FINAL EXAMINATION ‘- " " .‘ I ' Question 5. [20 MARKS] Part (a) [6 MARKS] Complete the following function: def switch-red_green(pic): ’ “Given a picture, return the same picture with the red and green channels switched. ) 2 ) Part (b) [5 MARKS] Complete the following nose test for switchxedgreenz def test_all_black(): ”’Test switch_red_green using a small (2 x 2) picture that is all black. It should return a picture that is all black.’ ’ ’ Page 6 of 20 CONT’D. .. FINAL EXAMINATION CSC 108E118 Part (c) [9 MARKS] Complete the following nose test for switch_red_green: def test_green_red_white(): ’ “Test make_histogram using a small (3 x 3) where one row is red, one row is green and one row is white. It should return a 3x3 image where the first row is green, the second row is red, and the third row is white.”’ Page 7 of 20 CONT’D. .. CSC108HIS FINAL EXAMINATION » : , Question 6. [8 MARKS] A matrix is represented as a list of rows, where each row is a list of numbers. For example, the following is an example of a matrix: 1 2 3 4 5 6 Complete the function below: def create_matrix(list, rows, cols): ”’Given two integers representing the number of rows and columns, and a list of numbers (whose length is equal to the product of variables rows and cols), return a list of lists representing a matrix of size rows x cols, where each sublist is a row of the matrix.” ’ Page 8 of 20 CONT’D. . . FINAL EXAMINATION CSC 108H18 Question 7. [20 MARKS] This question assumes that you have a class called Passenger. You do not need to write the class. The constructor for Passenger takes the name (string) of the passenger, the weights (list of floats) of the luggage of the passenger, and f_class (string) for the class the passenger will be flying in. Method __str-_ returns a string conveying information about passenger. An example string might be “Jim, flying coach, (5.2, 25.0)” where “Jim” is the passenger’s name, “coach” is the class, and 5.2 and 25.0 are the weights of the pieces of luggage Jim has brought along for his flight. You will write a new class called Flight. Part (a) [5 MARKS] Start defining the class Flight. It should include a constructor for that takes an integer representing the flight number, and a list of Passenger objects as an optional argument. If the argument is omitted, then an empty list is assumed. Page 9 of 20 CONT’D. . . CSC108H18 FINAL EXAMINATION Part (b) [4 MARKS] Write the _str_ method for Flight. The string that is returned should have the flight number, followed by the string representation of each passenger on a separate line. Part (C) [3 MARKS] Complete the method defined below: def add_passenger(self, name, class, luggage): "’Add a passenger with the given name, class, and luggage information to the list of passengers on this flight. ”’ Page 10 of 20 CONT’D. .. - I FINAL EXAMINATION CSC 108E118 Part (d) [8 MARKS] Assume that the class Passenger contains the following method. def luggage_weight (self) : “’Return the total weight of the passenger’s luggage as a float. ’ ” Complete the method below for the class Flight (use the method just described in your solution): def heavier(self, p1, p2): “’Return the passenger information (as a string) of which of passengers p1 and p2 are carrying more luggage on the current flight. If there is no passenger with the pl’s name or p2’s name, or both passengers have the same name, return ’Error’. ”’ Page 11 of 20 CONT’D. .. CSC 108E118 FINAL EXAMINATION 'T Question 8. [11 MARKS] This question continues with the class Flight from the previous question. Recall that Flight contains a list of passengers. Write a program that builds a GUI to allow a user to find which of two passengers is carrying more luggage for a flight. When the user pushes the button Submit the information of the heavier passenger is displayed. We have provided the starter code. Make sure to fill in the code requested in the comments and to use the variable names defined. Write any new functions you need at the end. Part (a) [3 MARKS] Given the starter code, give a rough sketch of what the GUI looks like in its present form. Part (b) [8 MARKS] Fill in the necessary code as requested in the comments to complete the program. from Tkinter import * from region import * # contains the classes from the previous question. if __name__ == ’__main__’: flight = Flighto flight.add_passenger("Jim", "coach", [5.2, 25.0]) flight.add_passenger("Sarah", "first class", [2.5, 27.1]) window = Tk() frame = Frame(window) frame.pack() pasleabel = Label(frame, text="Passenger 1: ") pass 1Labe1 . grid (row=0 , column=0) pass2Label = Label(frame, text="Passenger 2: ") passZLabel . grid(row=1 , column=0) paslentry = Entry(frame) Page 12 of 20 CONT’D. .. FINAL EXAMINATION CSC 108HIS paslentry.grid(row=O, column=1) passQEntry = Entry(frame) pass2Entry.grid(row=1, column=1) heavierDescrip = Labelerame, text="Heavier:") heavierDescrip.grid(row=2, column=0) # Add the label to display the passenger information. # Add the submit button. window.mainloop() # ADD ANY NEW FUNCTIONS HERE Page 13 of 20 CONT’D. .. CSC 108E118 FINAL EXAMINATION Question 9. [10 MARKS] Write a function, merge, that takes two lists as arguments. Each list is sorted in order from largest to smallest. The function returns a new list that contains all of the elements from both lists in order from smallest to largest. You have 5 options for answering. Indicate clearly which one you are attempting by circling the option below. 0 You can leave it blank. We will give you 0 marks. 0 You can write “I don’t know how to solve this question.” We will give you 2 marks! a You can solve it by using Python’s sort function. We will give you 3 marks. 0 You can solve it using a general sorting algorithm such as selection sort for a maximum of 5 marks. 0 You can solve it in linear time, where the elements of each list are moved only once for the full 10 marks. For the last three options, write the appropriate code for merge below. Page 14 of 20 CONT’D. . . A- - _ ‘ FINAL EXAMINATION CSC 108Hls [Use the space below for rough work. This page will not be marked, unless you clearly indicate the part of your work that you want us to mark. ] Page 15 of 20 CONT’D. .. CSC 108H18 FINAL EXAMINATION [Use the space below for rough work. This page will not be marked, unless you clearly indicate the part of your work that you want us to mark. ] Page 16 of 20 CONT’D. .. FINAL EXAMINATION CSC 108E118 [Use the space below for rough work. This page will not be marked, unless you clearly indicate the part of your work that you want us to mark. ] Page 17 of 20 CONT’D. .. CSC 108H1vS FINAL EXAMINATION Short Python function/ method descriptions: __builtins__: chr(i) -> character Return a string of one character with ordinal i; 0 <= 1 < 256. len(x) -> integer Return the length of the list or string x. maxCL) -> value Return the largest value in L. min(L) —> value Return the smallest value in L. open(name[, mode]) —> file object Open a file. ord(c) -> integer Return the integer ordinal of a one—character string. range([start], stop, [step]) -> list of integers Return a list containing the integers starting with stop and ending with stop - 1 with step specifying the amount to increment (or decrement). If start is not specified, the list starts at 0. If step is not specified, the values are incremented by 1. round(number[, ndigits]) -> floating point number Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Color: black RGB: 0, O, 0 blue RGB: 0, O, 255 green RGB: 0, 128, 0 red RGB: 255, 0, 0 white RGB: 255, 255, 255 dict: D.get(k) --> value Return the value associated with the key k in D. D.has_key(k) --> boolean Return True if k is a key in D and False otherwise. D.keys() -—> list of keys Return the keys of D. D.values() --> list of values Return the values associated with the keys of D. file: F.close() 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 is reached. F.read1ine([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. float: float(x) —> floating point number Convert a string or number to a floating point number, if possible. Page 18 of 20 CONT’D. .. FINAL EXAMINATION CSC 108HIS int: int(x) -> integer Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero. list: L.append(x) Append x to the end of the list L. L.index(value) -> integer Returns the lowest index of value in L. L.insert(index, x) Insert x at position index. L.remove(value) Removes the first occurrence of value from L. L.sort() Sorts the list in ascending order. Picture: get_blue(Pixel) --> int, get_red(Pixel) --> int, get_green(Pixel) -—> int Return the value of the specified color (between 0 and 255) in the given pixel. get_color(Pixel) -> Color Return the color of the pixel. get_height(Picture) -'> int Takes a picture as input and returns how many pixels high it is. get_width(picture) --> int Takes a Picture as input and returns how many pixels wide it is. get_pixel(Picture, x, y) --> Pixel Return the pixel at the location (x, y) in the given picture. get_pixels(Picture) --> list Takes a picture as input and returns the sequence of pixel objects in the picture. make_empty_picture(width, height) —-> Picture Return a blank (black) picture of the given dimensions. make_picture(filename) ——> Picture Create and return a picture from the contents of filename. pick_a_file() —-> string Launch a file chooser and return a string containing the name of the file that was selected. set_blue(Pixel, value), set_green(Pixel, value), set_red(Pixel, value) Set the specified color component in the given pixel to the given value. set_color(Pixel, color) Set the pixel to the color. show(Picture) Displays the picture. str: str(x) -> string Convert an object into its string representation, if possible. S.find(sub[,i]) -> integer Return the lowest index in S (starting at S[i], if i is given) where the string sub is found or -1 if sub does not occur in S. S.index(sub) -> integer Like find but raises an exception if sub does not occur in S. S isdigit() ~-> boolean Return True if all characters in S are digits and False otherwise. S.replace(old, new) ——> string Return a copy of string S with all occurrences of the string old replaced with the string new. Page 19 of 20 CONT’D. .. CSC 108H18 ' FINAL EXAMINATION S.rstrip([chars]) -> string 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() -—> string Return a copy of S with leading and trailing whitespace removed. Tkinter: Button: Button(parent, [text=],[textvariable=], [command=]) —-> button object Construct a button with the given parent. DoubleVar: DoubleVar() -> Tk float variable object Construct a Tkinter float variable. D.get() -> float Return the value of D. D.set(value) Set D to value. Entry: Entry(parent) --> entry object Construct an entry field with the given parent. E.delete(first, last) Delete text from first to last (non-inclusive). (Common first and last positions are 0 and END, respectively.) E.get() qw—-> string Return the text in the entry field E. Frame: Frame(parent) --> frame object Construct a frame widget with the given parent. IntVar: IntVar() -> Tk int variable object Construct a Tk int variable. I.get() -> int Return the value of I. I.set(value) Set I to value. StringVar: StringVar() --> Tk string variable object Construct a Tk string variable. S.get() --> string Return value of S. S.set(value) Set S to value. Window: Tk() --> window Return a new window widget. All Widgets: A.grid(row=r, column=c) Place widget A in row I and column c. A.pack() Place widget A below the last widget that was packed. Page 20 of 20 END OF EXAMINATION ...
View Full Document

Page1 / 20

Summer.2008 - (6‘ UNIVERSITY OF TORONTO O 4‘96 Faculty...

This preview shows document pages 1 - 20. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online