csc108h-d07 - UNIVERSITY OF TORONTO 6‘ Faculty of Arts...

Info iconThis preview shows pages 1–22. 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
Background image of page 21

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

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

Unformatted text preview: UNIVERSITY OF TORONTO 6‘ Faculty of Arts and Science DECEMBER EXAMINATIONS CSC 108H1F Duration —— 3 hours ’t Examination Aids: None Student Number: , , I 1 Last (Family) Name(s)v: First (Given) Name(s): Instructor: b ll (circle one) camp 6 Gries 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.) This final examination consists of 9 questions on 22 pages (including this one). When you receive the signal to start, please make sure that your copy of the examination is complete. Comments and docstrings are not required except where indicated, although they may help us mark your answers. They may also get you part marks if you can’t figure out how to write the code. You do not need to put import statements in your answers. You may not use break or continue on this exam. If you use any space for rough work, indicate clearly what you want marked. Assume all input is valid unless otherwise indicated; there is no need to error—check. Good Luck! Page 1 MARKING GUIDE #1: #2: #3: #4: #5: #6: #7; #8: #9; TOTAL: _/ 6 _/ 6 _/ 8 _/ 8 _._._/ 10 ____/16 ___/16 _____/10 _____/10 /90 CONT’D. .. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 Question 1. [6 MARKS] Write a function warmest-day that takes a list of str days and float temperatures in the format of the example below and returns the day with the highest temperature. L = [‘Monday’, 15.4, ‘Tuesday’, 17.1, ‘Wednesday’, 16.9] You may assume the list is non-empty. If the list contains two days with the warmest temperature, return either one. Page 2 of 22 V CONT’D. .. DECEMBER 2007 FINAL EXAMINATION CSC 108H1F Question 2. [6 MARKS] In the table below, trace the variable values during execution of mystery(‘ever’ , ‘e’). 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. Show variable values after each line has executed: def mystery(a, b): i = 0 During lst iteration uring 2nd iteration uring last iteration while a.find(b, i) >= 0: i = a.find(b, i) c = a[:i] d = a[i:] a = c + b + d i += 2 return a value returned: Page 3 of 22 CONT’D. .. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 Question 3. [8 MARKS] Write docstrings for the following functions. Include assumptions about the parameter values. Part (a) [4 MARKS] def enigma(L): 2)) ))} a = min(L) loc = L.index(a) L.remove(a) b = min(L) L.insert(loc, a) return b HereiSIMIexanuflecfizicaH:enigma([’michael’, ’jen’, ’paul’, ’andrew’]) Part (b) [4 MARKS] def mystery(L, d): ))} 7” res = {} for v in L: if v in d: res[d[v]] = v return res HmeEanmmeedacakmwmquB,4,5,6,7],{%’w,3:%’,5flc%) Page 4 of 22 CONT’D. .. DECEMBER 2007 FINAL EXAMINATION CSC 108H1F Question 4. [8 MARKS] Part (a) [4 MARKS] Complete the following function: def find_keys(d, v): ”’Return a list of keys in dictionary d that are associated with value v.”’ Part (b) [4 MARKS] ‘ Fill in the rest of the table of test inputs and expected results below. We have filled in the first row7 indicating that a call to find_keys({}, 1) should return the empty list. 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 dictionary. {} Expected result H Page 5 of 22 CONT’D. .. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 Question 5. [10 MARKS] Part (a) [4 MARKS] Complete the following function: def swap_blue(pic1, pic2): ”’Swap the blue color values of all the pixels in picl with the blue color values of the corresponding pixels in pic2. Assume that pic1 and pic2 have the same width and height.”’ Part (b) [6 MARKS] Complete the following nose test for swap_blue: def test_swap_blue(): ”’Test swap_blue using two small (2 x 2) pictures, one black and one blue. After swap_blue has been called on the two pictures, the black picture should have turned blue, and the blue picture should have turned black.”’ Page 6 of 22 CONT’D. .. DECEMBER 2007 FINAL EXAMINATION CSC 108H1F Question 6. [16 MARKS] This question has you write a program to manage an inventory. The question has three parts. Part (a) [4 MARKS] Complete the following function: def read_inventory(f): ”’Given an open file that contains lines of the form ITEM,CDUNT,COST (where ITEM is a str, COUNT is an int, and COST is a float), return a dictionary in which the ITEMS are the keys and the values are (COUNT, COST) tuples. The ITEMS are unique.”’ Part (b) [2 MARKS] Complete the following function, which operates on a dictionary like the one returned by read-inventory. def set_inv_data(inv_dict, item, Tkvar_count, Tkvar_cost): ”’inv_dict is a dictionary with strings as keys and tuples of int, float pairs as values. Set the Tkvariables to the count and cost associated with item in inv_dict. Tkvar_count is an IntVar, and Tkvar_cost is a DoubleVar.”’ Page 7 of 22 CONT’D. .. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 Part (c) [10 MARKS] Write a program that builds a GUI to present inventory management information. The inventory data that your program will need is in the file inv_data.txt; this file contains lines of the form ITEM,COUNT,COST. Your GUI should look like the example below. Cost: 0.00 When the user pushes the button Check, the count and cost associated with the item entered into the Entry widget should be displayed. We have provided some starter code to import the modules you need and to define the window and frame. Make sure to fill in the code requested in the comments and to use the variable names defined. from Tkinter import * import inv_he1pers # Contains the helper functions from parts (a) and (b) # Open the inventory file and make the inventory dictionary. # ADD CODE BELOW # Create a Tkinter window and add the first label. window = Tk() frame = Frame(window) frame.pack() itemLabel = Label(frame, text="Item: ") itemLabel.grid(row=O, column=0) # Add the text entry box to the frame. # ADD CODE BELOW Page 8 of 22 CONT’D. .. DECEMBER 2007 FINAL EXAMINATION CSC 108H1F # Add the second row of labels. # ADD CODE BELOW # Add the button to fetch the count and cost information of the item specified by the user. # ADD CODE BELOW. window.mainloop() Pag390f22 CONTbH. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 Question 7. [16 MARKS] This question has you write a class called vendinanachine. The question has three parts. Part (a) [8 MARKS] Start defining class vendingmachine; include a constructor and 8. __str__ method. The constructor takes a list of (item, price , num_in_stock) tuples where item is a str, price is a float, and num_in_stock is an int. Method -_str__ returns a string representing the current inventory of the machine. For example, given the inventory [("soda" , 1.0, 10), ("chips" , 0.7, 6), ("crackers" , 0.25, 3)], the return value is: "soda $1.00 (10)\nchips $0.70 (6)\ncrackers $0.25 (3)\n" Part (b) [3 MARKS] Complete the following helper method for vendinanachine. def _find_item(self, item_name): ”’item_name is a str that represents an item sold by the vending_machine; return the index of the tuple in the inventory list whose first element is item_name.”’ Page 10 of 22 . CONT’D. .. DECEMBER 2007 FINAL EXAMINATION CSC 108H1F Part (c) [5 MARKS] Define three methods for the vendinanachine class. Each method takes self and a str as parameters. You should call method .find_item from part 0 price: Return the price of the given item as a float. o has_item: Return True if the requested item is in stock (num_in_stock is greater than zero) and False otherwise. 0 vend: If the given item is in stock7 decrement the number in stock and return True. If the item is not in stock, return False. For all three items, you may assume that the user will only ask for items that exist in the inventory list. Page 11 of 22 CONT’D. .. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 Question 8. [10 MARKS] Complete the following functions. Part (a) [6 MARKS] def encrypt_character(c, mapping=): ”’Return the encrypted version of lowercase character c (a string). If the mapping is not specified, the character’s encrypted value is the next character in the alphabet: ’a’ is encrypted as ’b’, ’b’ as ’c’, and so on. ’2’ is encrypted as ’a’. If the mapping is specified, it is used for the encryption: it is a list of lists where each element is a 2—item list containing a character and its encrypted version (both of type str). This list will contain c as a character.”’ Page 12 of 22 CONT’D. .. DECEMBER 2007 FINAL EXAMINATION ’ CSC 108H1F Part (b) [4 MARKS] def encrypt(f, mapping=): ”’Given an open file f that contains a text message, return the encrypted version of that message (as a string). If the mapping is not specified, the character’s encrypted value is the next character in the alphabet: ’a’ is encrypted as ’b’, ’b’ as ’c’, and so on. ’2’ is encrypted as ’a’. If the mapping is specified, it is used for the encryption: it is a list of lists where each element is a 2—item list containing a character and its encrypted version (both of type str). The mapping will contain all of the characters in the message. The message will contain only lowercase characters, newlines, and spaces, and the mapping will contain only characters. In the encrypted version, spaces and newlines remain unchanged.”’ Page 13 of 22 CONT’D. .. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 Question 9. [10 MARKS] The Dutch national flag is divided into three horizontal areas: Someone has given you a picture of the flag with the columns scrambled: in each column, the reds, whites, and blues have all been mixed up. (No pixels have been moved left or right; only up and down.) The program on the opposite page fixes the picture—but the function f ix-column is not yet written. For example, if you are given the picture on the left below (where “R” means a red pixel, “W” a white, and “B” a blue), then the program will fix the picture so that it looks like the picture on the right. RWBRRB RRRRRR WRRBRB RRRRRR BRWRWW ~> WWWWWW BBRBBR BBBBBB RBBWBR BBBBBB Your task is to write the code for fix_column on the next page. You can’t remember if the flag’s bands of colour have the same height, so you can’t just make the top third red. You have five 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! 0 You can solve it by counting colours in a column and setting the pixel values according to those counts for a maximum of 5 marks. 0 You can solve it using a general sorting algorithm such as insertion sort for a maximum of 7 marks. 0 You can solve it in linear time, using get_color on each pixel exactly once (not counting its use in swap_color), for the full 10 marks. For the last three options, put the appropriate code into f ix_row on the next page. Page 14 of 22 CONT’D. .. DECEMBER 2007 FINAL EXAMINATION CSC 108H1F from picture import * def swap_color(pic, col, i, j): ”’Swap the colours of the two pixels in pic at locations (col, i) and (col, j).”’ p1 = get‘pixel(pic, col, i) p2 = get_pixel(pic, col, j) c = get_color(p1) set_color(p1, get_color(p2)) set_color(p2, c) def fix_column(pic, col): ”’Fix column col of pixels in picture pic so that the red pixels are at the top, the white ones in the middle, and the blue ones at the bottom.”’ def fix_f1ag(pic): ”’Sort each column of pixels in pic so that the red pixels are at the top, the white ones in the middle, and the blue ones at the bottom.”’ for col in range(get_width(pic)): fix_column(pic, col) Page 15 of 22 CONT’D. .. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 [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 22 CONT’D. .. DECEMBER 2007 FINAL EXAMINATION CSC 108H1F [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 22 CONT’D. .. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 [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 18 of 22 CONT’D. .. DECEMBER 2007 FINAL EXAMINATION CSC 108H1F [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 19 of 22 CONT’D. .. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 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. max(L) -> 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: O, 0, 0 blue RGB: O, O, 255 green RGB: O, 128, 0 red RGB: 255, O, 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.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. float: float(x) -> floating point number Convert a string or number to a floating point number, if possible. Page 20 of 22 CONT’D. .. DECEMBER 2007 FINAL EXAMINATION CSC 108H1F 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 21 of 22 CONT’D. .. CSC 108H1F FINAL EXAMINATION DECEMBER 2007 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.de1ete(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 22 of 22 END OF EXAMINATION ...
View Full Document

This note was uploaded on 08/04/2011 for the course CSC 108 taught by Professor Gries during the Fall '08 term at University of Toronto.

Page1 / 22

csc108h-d07 - UNIVERSITY OF TORONTO 6‘ Faculty of Arts...

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

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