csc108_final_2012f

22
NAME (PRINT): Last/Surname First IGiven Name STUDENT#: _____________________ SIGNATURE: _______________ UNIVERSITY OF TORONTO MISSISSAUGA DECEMBER 2012 FINAL EXAMINATION CSC108H5F Introduction to Computer Programming Daniel Zingaro & Gerhard Trippen 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 begun. This exam has 10 questions, for a total of 100 points, and 22 pages, please check it.

Upload: examkiller

Post on 27-Dec-2015

20 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CSC108_Final_2012F

• •

NAME (PRINT): .-:::~:::::=::-----------;;:.,.--;-;;;o;---.....-;----------Last/Surname First IGiven Name

STUDENT#: _____________________ SIGNATURE: ______________ _

UNIVERSITY OF TORONTO MISSISSAUGA DECEMBER 2012 FINAL EXAMINATION

CSC108H5F Introduction to Computer Programming

Daniel Zingaro & Gerhard Trippen 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 ofyour 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 begun.

This exam has 10 questions, for a total of 100 points, and 22 pages, please check it.

Page 2: CSC108_Final_2012F

CSCI08H5F Final Examination 2012 Fall Term

For Instructor Use:

Question Points Score

1 12L

2 8

3 10

4 9

5 18

I 6 8i

7 5I I I 8 8I

9 12

10 10

Total: 100

Page 2 of 22

Page 3: CSC108_Final_2012F

CSCI08H5F Final Examination 2012 Fall Term

1. (12 points)

Each of the code sequences below runs without error. Show the output for each.

(a) (2 points) x = a for i in range(5):

x += 3 print(i, end=")

print (x)

(b) (2 points) char = >z' s = >, t = 'abc' for char in 'abc':

s = char + a + char t.replace(char, 'x')

print(s) print(t)

(c) (2 points) composers = [>Kondo', 'Tamura>] composers2 = composers compoaers2[O] = 'Ito' composers2[1] = composers[O] print (compoaers) print (composers2)

Page 3 of 22

Page 4: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

(d) (2 points) composers = [>Kondo> > >Tamura>] composers2 = composers[:] composers2.append(composers) print (composers) print (composers2)

(e) (2 points) composers = [>Kondo', 'Tamura', ['Bach', >Mozart>]] composers2 = composers[:] composers2[1] = 'Nagamatsu' composers2[2] [1] = 'Brahms' print (composers) print (composers2)

(f) (2 points)

Assume that file junk. txt contains exactly the following three lines: ab cd ef

Here is code that operates on this file: f = open('junk.txt'. 'r') d = {} for line in f:

d[line[O]] 1 print (d)

Page 4 of 22

Page 5: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

2. (8 points)

The admission price to a theatre depends on whether you go during the afternoon or in the evening, and whether you go on a weekday or weekend. The following table gives the admission prices:

I Time I weekda~i:eekend I afternoon $50 $100

evening $100 $100 I I

(a) (3 points) Write the following function that returns True iff the admission price is $100. Write only the function body, not the remainder of the docstring. def is_expensive (weekday , evening):

"'(baal, bool) -> bool Return True iff the admission price is $100. weekday is True on weekdays and False on weekends. evening is True in evenings and False in afternoons. , , ,

Page 5 of 22

Page 6: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

(b) (5 points) Read the following function and then follow the first four steps of the Design Recipe to complete the function header and docstring. Give two exam­ples in your docstring.

def ) , ,

, , , index = len(s) - 1 while index >= 0 and s[index] != c:

index -= 1 return index >= len(s) II 2

Page 6 of 22

Page 7: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

3. (10 points)

Consider the following string: qqabcdefghibcdefghjkljkl

One way to reduce the length of this string is to observe that it has quite a bit of repetition. If we can reference an earlier part of the string rather than duplicate it, we can save some space. Here is a compressed string that uses this idea:

qqabcdefghi#8,7 jkl#2,3

To decompress this string back to the original, we copy characters into a new string new until we see a number sign (#). Following each # we will find the number of characters that we have to look back in new, a comma, the number of characters to copy from that previous position, and then a space separator. To decompress the string above, we would begin by copying all characters until the first #:

qqabcdefghi

Then, we see #8,7, which means "move 8 characters from the end and copy 7 char­acters from there". Moving left 8 characters starting from the i brings us to the b, and copying 7 characters from there gives us bcdefgh. Appending that to what we had so far, we get:

qqabcdefghibcdefgh

We would then continue processing the decompression at the next character j. To make sure you understand what's happening, you are advised to decompress the remainder of the string by hand before continuing!

(a) (4 points) Write the following function. Note that x or y below could contain multiple digits. def extract_nums(s);

"'(str) -> tuple of (int, int) s is of the form "x,ylt (without a space). where x and y can be converted to ints. Return a tuple of the two ints from s. »> extract_nums('4,5') (4, 5) , , ,

Page 7 of 22

Page 8: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

(b) (6 points) Write the following function. def decompresses):

"'(str) -> str Return the result of decompressing s. »> decompress('qqabcdefghi#8.7 jkl#3.3 ,) 'qqabcdefghibcdefghjkljkl' , , ,

Page 8 of 22

Page 9: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

4. (9 points)

A subsequence of a list is different from a segment of a list. A subsequence is a list of elements in the same order as in the list, but the elements are not necessarily contiguous. For example, in the list [2. 4, 6], one of the subsequences is [2, 4] and another is [2, 6].

An upsequence is a subsequence in which each element is at least as big as the element to its left.

(a) (2 points) Consider the list [2, 4. 3, 5]. Is [2. 3, 4] an upsequence of this list? 0 Yes 0 No

(b) (5 points) Write the body of the following function. Do not complete the doc­string. def is_upsequence(lst. upseq):

"'(list of int, list of int) -> bool Return True iff upseq is an upsequence of 1st. , , ,

(c) (2 points) Consider this function and docstring: def is_sequence(lst, seq):

"'(list of int, list of int) -> bool Return True iff seq is a sequence of 1st. , , ,

Would this function be more or less efficient (in terms of orders of complexity) than the is_upsequence function you wrote above? Briefly explain. Do NOT write code. Please only explain.

Page 9 of 22

Page 10: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

5. (18 points)

Given a wordlist and a letter, a word family consists of the words in the wordlist . that have the letter in the same position(s).

For example, here is a wordlist: ally beta cool deal else good. Choosing the letter e, the following are the word families that result from this wordlist. Note how all words in each word family have the same pattern:

• Family ----: ally cool good • Family -e--: beta deal

• Familye--e: else

The biggest family here is----, because it has the most words of anyfamily. If multiple families have the most words, then there are multiple biggest families.

On the following pages, you will write several functions related to words and families. Then, you will use these functions to write a program that determines the number of guesses it takes a person to prune a wordlist down to a single word. When you see opportunities to reuse earlier functions in later functions, please do so rather than repeating code.

(a) (3 points) Complete the following function according to its docstring descrip­tion. def get_words_of_lengthCword_file. length):

"'Cfile, int) -> list of str word_file contains one word per line. Return a list that contains each word of length letters from word_file with leading and trailing whitespace removed. , , ,

Page 10 of 22

Page 11: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

(b) (2 points) Complete the following function according to its docstring descrip­tion. def get_family(word, letter):

"'(str, str) -> str Return the family for word based on letter. »> get_family('sehala', 'a') 'sch-l-' , , ,

(c) (4 points) Complete the following function according to its docstring descrip­tion. def generate_families(word_list, letter):

"'(list of str, str) -> diet of {str: list of str} Given a list of words and a letter, return a diet where each key is a family and each value is the list of words in that family. »> generate_families(['ally', 'beta', 'cool', 'deal', 'else',

, good'], ' e ' ) {'-e--': ['beta', 'deal'], ,----': ['ally', 'cool', 'good'],

'e--e': ['else']} , , ,

Page 11 of 22

Page 12: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

Cd) (5 points) Complete the following function according to its docstring descrip­tion. def words_from_biggest_family(fams):

"'(diet of {str: list of str}) -> list of str Given a diet of family information, return the list of words belonging to the biggest family. If there are multiple biggest families, choose one such family randomly and return its list of words. »> words_from_biggest_familY({'~e~~': ['beta', 'deal'],

[ 'ally', , cool', 'good'], ['else ']}

[, ally', 'cool', 'good'] , , ,

Page 12 of 22

Page 13: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

(e) (4 points) In this part, you will write code to play the following game:

• The player enters the length of the words to use, and the program reads a list of words of that length

• The player guesses a letter • Families are generated, and the current wordlist is replaced by the wordlist

of the largest family

• The player keeps guessing letters until the wordlist has only one word re­maining, at which point she wins

• Finally, the player is told her total number of guesses

Here is a sample execution of the game: Please enter the word length: 4 Words remaining: ['ally'. 'beta', 'cool', 'deal', 'else'. 'good'] Please enter your next guess: 0

Words remaining: ['ally'. 'beta', 'deal', 'else'] Please enter your next guess: e Words remaining: ['beta', 'deal'] Please enter your next guess: 1 You win! It took you 3 guesses.

The beginning of the code has been written for you. Finish the code so that it plays the game described here. Assume words. txt exists and consists of one word per line. Do not add error-checking anywhere. word_file = open('words.txt') length = int (input ("Please enter the word length: "»

Page 13 of 22

Page 14: CSC108_Final_2012F

·.

CSC108H5F Final Examination 2012 Fall Term

6. (8 points)

We are going to encode words using four-character strings that are composed of one letter followed by three digits. (Phonetic algorithms use techniques like this to encode similarly-sounding words with the same encoding.) Each letter is encoded by a number, according to the following table:

Letter Iabcdefghijklmnopqrstuvwxyz Encoding 01230120022455012623010202

For example, this means that letter a is encoded by 0, b by 1, e by 2, d by 3, e by 0, etc. The algorithm we will use to generate a four-character encoding ene for a word is as follows:

1. For each character in the word, add its encoding to ene iff the current rightmost character of ene is .different from that encoding

2. After adding all encodings, add the first character of the word to the left of ane

3. Remove all 0 characters from ene

4. If ene contains fewer than four characters, pad it with 0 characters on the right until it is four characters

5. Return the first four characters of ene

For example, consider the word zelda. Step 1 results in the string 20430. Step 2 prepends the z, resulting in z20430. Step 3 removes the Os to get z243. Since this string is already length 4, step 4 does no padding, and step 5 returns the string z243. On the next page, you will write the following function. def encode_word(word):

"'(str) -> str word is a str composed entirely of letters. Return the encoding of word according to the rules described. »> .encode_word('zelda') 'z243' , , ,

(a) (3 points) Assume that we want to test encode_word. Describe three test cases that each test different "categories" of inputs. To describe each test case, give the str that you would pass to encode_word, the return value you expect, and the purpose of the test case. Do not write any code. On the next page, we have given you one test case as an example; add three more in that table.

Page 14 of 22

Page 15: CSC108_Final_2012F

·. CSC108H5F Final Examination 2012 Fall Term

IValue of word IReturn value IPurpose of this test case

"zelda" 'z243' no duplicates

(b) (5 pOints) Now write function encode_word. Don't worry about copying the docstring. You may assume the existence of function letter_encoding that takes a letter and returns its numeric encoding as a string. For example, letter_encoding('a') returns '0' because the encoding for a is O. def encode_word(word):

Page 15 of 22

Page 16: CSC108_Final_2012F

·.

CSC108H5F Final Examination 2012 Fall Term

7. (5 points) Write the following function according to its docstring description.

def make_rows(lst, num): "'(list of int, int) -> list of (list of int) Return a list of lists of elements from 1st, where each sublist is the next num elements from 1st. If the length of 1st is not a multiple of num, the final sublist will have fewer than num elements. »> make_rows([2. 4, 6, 8, 10, 12],3) [[2, 4, 6], [8, 10, 12]]

Page 16 of 22

Page 17: CSC108_Final_2012F

I

CSC108H5F Final Examination 2012 Fall Term

8. (8 points) Majority rule is a voting system where a candidate must obtain more than half of the votes to be declared the winner. If there is no candidate with the majority of votes, then there is no winner. Like plurality, ballots are single-candidate. However, majority rule is not the same as plurality; make sure you understand why before continuing.

Write a function called maj ority..rule that takes a list of strings (the ballots) and returns the majority winner. If there is no majority winner, the function should return None.

In this question, we are not dealing with the four parties from assignment 2. The list of strings could contain any number of different candidate names.

You must include all steps of the design recipe in your solution (Le., examples, con­tract, header, description, body); you will lose the majority of marks if you write only code and do not include the recipe components.

Page 17 of 22

Page 18: CSC108_Final_2012F

·. CSC108H5F Final Examination 2012 Fall Term

9. (12 points)

Consider the following two classes. class Ring(object):

"'A ring with a name and mana,'"

def __init__ (self, name, mana): "'(str, int) -> Ring Create a Ring with the given name and mana. , , , self.name = name self.mana = int(mana)

def lose_one_mana(self): "'() -> NoneType Remove 1 mana from this Ring's mana. , , , self.mana = max(O, self.mana - 1)

def __str__ (self): , , '() -> str Return a string representation of this Ring. , , , return 'Ring: {OJ, mana: {l}'.format(self.name, self.mana)

class Player(object): "'A player with a name and two rings.'"

def __init__ (self, name, ring1, ring2): "'(str, Ring, Ring) -> Player Create a Player with name wearing two rings, ring1 and ring2. , , , self.name = name self.rings = [ring1, ring2]

(a) (2 points) Create a Ring object and make rl refer to that object. The ring's name should be "gasha ring" and its mana should be 50.

(b) (2 paints) Write a method call that removes one mana from the ring referred to by r1.

Page 18 of 22

Page 19: CSC108_Final_2012F

• t

CSC108H5F Final Examination 2012 Fall Term

(c) Write the following new methods for the Player class. 1. (3 points)

def __str__ (self): , "0 -> str Return a string representation of this Player. The string includes the player's name and the names and manas of both of their rings. , , ,

ii. (3 points) def __gt__ (self. player2):

"'(Player) -> bool Return True iff this Player has more mana than player2. A player's mana equals the sum of the mana of the two rings that they are wearing. , , ,

Cd) (2 points) I propose that Ring should inherit from Player rather than object. Is this reasonable? Answer yes or no and provide a one-sentence explanation.

Page 19 of 22

Page 20: CSC108_Final_2012F

, .

CSC108H5F Final Examination 2012 Fall Term

10. (10 paints)

Throughout this question, assume that we are sorting lists into non-descending order. Do not guess on the yes/no questions. There is a one-mark deduction for incorrect answers on yes/no questions.

(a) Assume that a sort is being performed on a list and that we are focused on three consecutive passes (not necessarily the first three). The contents of the list after the first and third of these passes are shown, but the contents after the second pass are hidden. [3, 4, 5, 15, 3, 18, 11, 6] [***hidden] [3,3,4,5,15,18.11,6]

i. (1 point) Could we be doing selection sort? Check one. 0 Yes o No ii. (1 point) Could we be doing insertion sort? Check one. 0 Yes o No

iii. (1 point) Could we be doing bubble sort? Check one. 0 Yes o No

(b) (2 points) Give an example of a list for which insertion sort requires fewer comparisons than selection sort.

(c) (3 points) Here is an idea for a sort that is a variation of selection sort. On each pass:

• Find the smallest and largest values anywhere in the unsorted part • Swap the smallest value with the leftmost value in the unsorted part, and

swap the largest value with the rightmost value in the unsorted part

Sort the following list using this idea. Clearly show the contents of the list after each pass. [11, 20, 1991, 4. 13, 1992]

(d) (2 points) Which of the following characterizes the runtime of the sort described above? Check one. 0 linear 0 quadratic 0 cubic

Page 20 of 22

Page 21: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

Short Python function/method descriptions:

__builtins__ : input([prompt]) -) str

Read a string from the user. The trailing newline is stripped. The prompt string, if given, is printed before reading.

len (x) -) int Return the length of the list, tuple, dict, or string x,

max(iterable) -> object max(a, b, c, .. ,) -> object

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

min(iterable) -> object min(a, b, c, ... ) -> Object

With a single iterable argument, return its smallest item, With two or more arguments, return the smallest argument.

print (value, . ,., sep=' " end='\n') -> NoneType Prints the values. Optional keyword arguments: sep: string inserted between values, default a space. end: string appended after the last value, default a newline.

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

range([start], stop, [step]) -> list-like-object of int Return 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.

dict: D[k] -) Object

Return the value associated with the key k in D. D.pop(k)

Remove key k and its value from D. Return D[k] . k in d -> bool

Return True if k is a key in D and False otherwise. D.get(k) -> object

Return D[k] if k in D, otherwise return None. D.keys() -> list-like-object of object

Return the keys of D. D.values() -> list-like-object of object

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

Return the (key, value) pairs of D, as 2-tuples.

file: F.close() -> NoneType

Close F. F .readO -> str

Read until EOF (End Of File) is reached, and return as a string. F.readline() -> str

Read and return the next line from F, as a string. Retain newline. Return an empty string at EOF (End Of File).

Page 23 of 24 '

Page 22: CSC108_Final_2012F

CSC108H5F Final Examination 2012 Fall Term

list: x in L -> bool

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

Append x to the end of L. L.index(value) -> int

Return the lowest index of value in L. L.insert(index, x) -> NoneType

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

Remove and return the last element from L. L.remove(value) -> NoneType

Remove the first occurrence of value from L. L.reverse() -> NoneType

Reverse L *IN PLACE*. L.sort() -> NoneType

Sort L in non-descending order.

str: x in s -> bool

Return True if x is in s and False otherwise. str(x) -> str

Convert an object x into its string representation, if possible. S.count(sub[, start[, end]]) -> int

Return the number of non-overlapping occurrences of substring sub in S[start:end]. Optional arguments start and end are interpreted as in slice notation.

S.find(sub[, i]) -> int ~

Return the lowest index in S (starting at SCi], if i is given) where the string sub is found or -1 if sub does not occur in S.

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

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

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

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

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

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

S.split([sep]) -> list of str 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() -> str Return a copy of S with leading and trailing whitespace removed.

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

Page 24 of 24 End of exam.