Вы находитесь на странице: 1из 22

NAME(PRINT):

Last/Surname First IGiven Name


STUDENT#:
_____________________ SIGNATURE: ______________ _
UNIVERSITYOFTORONTOMISSISSAUGA
DECEMBER2012FINALEXAMINATION
CSC108H5F
IntroductiontoComputerProgramming
DanielZingaro& GerhardTrippen
Duration 3hours
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.
CSCI08H5F Final Examination 2012 Fall Term
ForInstructorUse:
Question Points Score
1 12
L
2 8
3 10
4 9
5 18
I
6 8
i
7 5
I I
I
8 8 I
9 12
10 10
Total: 100
Page2 of22
CSCI08H5F FinalExamination 2012 Fall Term
1. (12 points)
Eachofthe codesequences belowrunswithouterror. Showtheoutputfor 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)
Page3 of22
CSC108H5F FinalExamination 2012 FallTerm
(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)
Assumethatfile junk.txtcontainsexactlythefollowing threelines:
ab
cd
ef
Here iscode thatoperatesonthisfile:
f =open('junk.txt'. 'r')
d ={}
for line in f:
d[line[O]] 1
print (d)
Page4 of22
CSC108H5F FinalExamination 2012 Fall Term
2. (8 points)
Theadmissionpricetoa theatredependsonwhetheryougo duringtheafternoonor
in the evening, andwhether you go on a weekday or weekend. Thefollowing table
gives theadmissionprices:
I Time I I
afternoon $50 $100
evening $100 $100
I
I
(a) (3 points) WritethefollowingfunctionthatreturnsTrueifftheadmissionprice
is $100. Writeonlythefunction body, nottheremainder ofthedocstring.
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.
, , ,
Page5 of22
CSC108H5F FinalExamination 2012 FallTerm
(b) (5 points) Readthefollowingfunctionandthenfollow thefirst four stepsofthe
Design Recipe tocompletethefunction header anddocstring. Give twoexam-
plesinyourdocstring.
def
) , ,
, , ,
index =len(s) - 1
while index >= 0 and s[index] != c:
index -= 1
return index >= len(s) II 2
Page6 of22
CSC108H5F FinalExamination 2012 Fall Term
3. (10 points)
Considerthefollowing string:
qqabcdefghibcdefghjkljkl
One way to reduce the length ofthis stringis toobserve that it has quite a bit of
repetition. If we canreference anearlier partofthestringrather thanduplicateit,
we cansavesomespace. Here is a compressedstringthatuses thisidea:
qqabcdefghi#8,7 jkl#2,3
To decompressthis stringbacktotheoriginal, we copy charactersintoa newstring
new until we see a number sign (#). Following each # we will find the number of
charactersthatwe have tolook backinnew, a comma, thenumber ofcharactersto
copy from that previous position, and then a space separator. To decompress the
stringabove, we wouldbeginby copying all characters untilthefirst #:
qqabcdefghi
Then, we see#8,7, which means "move8 charactersfrom theend andcopy7 char-
acters from there". Moving left 8 charactersstartingfrom the i brings us to theb,
andcopying 7 characters from there gives us bcdefgh. Appendingthat towhat we
hadsofar, we get:
qqabcdefghibcdefgh
We would thencontinue processing the decompression at thenext character j. To
make sure you understand what's happening, you are advised to decompress the
remainderofthestringbyhand before continuing!
(a) (4 points) Write the following function. Note that x ory below could contain
multipledigits.
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 of22
CSC108H5F FinalExamination 2012 Fall Term
(b) (6 points) Writethefollowing function.
def decompresses):
"'(str) -> str
Return the result of decompressing s.
> decompress('qqabcdefghi#8.7 jkl#3.3 ,)
'qqabcdefghibcdefghjkljkl'
, , ,
Page8of22
CSC108H5F FinalExamination 2012 FallTerm
4. (9 points)
A subsequenceofa list is different from a segment of a list. A subsequence is a
listofelementsinthesameorderas inthelist, buttheelementsarenotnecessarily
contiguous. For example, in thelist [2. 4, 6], one ofthesubsequences is [2, 4]
andanotheris [2, 6].
An upsequence is a subsequence in which each element is at least as big as the
elementtoitsleft.
(a) (2 points) Considerthelist [2, 4. 3, 5]. Is [2. 3, 4] anupsequenceofthis
list? 0 Yes 0 No
(b) (5 points) Writethe body ofthefollowing function. Donot completethedoc-
string.
def is_upsequence(lst. upseq):
"'(listof int, list of int) -> bool
Return True iff upseq is an upsequence of 1st.
, , ,
(c) (2 points) Consider thisfunction anddocstring:
def is_sequence(lst, seq):
"'(listof int, list of int) -> bool
Return True iff seq is a sequence of 1st.
, , ,
Would this function bemore or less efficient (in terms ofordersofcomplexity)
thantheis_upsequencefunction youwrote above? Briefly explain. Do NOT
writecode. Pleaseonlyexplain.
Page9 of22
CSC108H5F FinalExamination 2012 FallTerm
5. (18 points)
Given a wordlist and a letter, a word familyconsists ofthe words in thewordlist
. thathavetheletterinthesameposition(s).
For example, here is a wordlist: ally beta cool deal else good. Choosing the
lettere, thefollowing arethewordfamilies thatresultfrom thiswordlist. Notehow
all wordsineachwordfamily havethesamepattern:
Family ----: ally cool good
Family -e--: beta deal
Familye--e: else
Thebiggest familyhereis----,becauseithasthemostwordsofanyfamily.
If multiplefamilieshavethemostwords, thentherearemultiplebiggestfamilies.
Onthefollowingpages,youwillwriteseveralfunctionsrelatedtowordsandfamilies.
Then,youwillusethesefunctionstowritea programthatdeterminesthenumberof
guesses it takes a person to prunea wordlist down to a single word. Whenyou see
opportunities to reuse earlier functions in later functions, please do so rather than
repeatingcode.
(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 of22
CSC108H5F FinalExamination 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):
"'(listof 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 of22
CSC108H5F FinalExamination 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.
> ['beta', 'deal'],
['ally', ,cool', 'good'],
['else']}
[, ally', 'cool', 'good']
, , ,
Page12 of22
CSC108H5F FinalExamination 2012 Fall Term
(e) (4 points) Inthis part,youwill writecodetoplaythefollowing game:
Theplayerenters thelength ofthewords to use, and theprogramreadsa
listofwords ofthatlength
Theplayerguesses a letter
Familiesaregenerated, andthecurrentwordlist is replacedbythewordlist
ofthelargestfamily
The player keeps guessing letters until the wordlist has only one word re-
maining, atwhich pointshewins
Finally, theplayer istoldher totalnumberofguesses
Hereis a sampleexecutionofthegame:
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.
Thebeginningofthecode has beenwrittenfor you. Finish thecodeso thatit
plays the game described here. Assume words.txtexists and consists ofone
wordperline. Donotadderror-checkinganywhere.
word_file = open('words.txt')
length = int(input("Please enter the word length: "
Page13of22
.
CSC108H5F FinalExamination 2012 Fall Term
6. (8 points)
We are going to encode words using four-character strings that are composed of
one letterfollowed bythreedigits. (Phonetic algorithms use techniques like thisto
encodesimilarly-soundingwords withthesameencoding.)
Eachletteris encodedbya number, accordingtothefollowing table:
Letter Iabcdefghijklmnopqrstuvwxyz
Encoding 01230120022455012623010202
Forexample, thismeans thatlettera is encoded by0, b by 1, e by2, d by3, e
by0, etc.
Thealgorithmwe will use togeneratea four-characterencodingenefor a word
is asfollows:
1. For each character in the word, add its encoding to ene iff the current
rightmost characterofeneis.different from thatencoding
2. Afteraddingallencodings, addthefirst characteroftheword totheleftof
ane
3. Removeall0 charactersfrom ene
4. If ene containsfewer thanfour characters, paditwith0 characterson the
right untilitisfour characters
5. Returnthefirst four charactersofene
Forexample, considerthe word zelda. Step 1 results inthestring20430. Step
2prependsthez, resultinginz20430. Step3 removes theOs toget z243. Since
this stringis already length 4, step 4 does no padding, and step 5 returns the
stringz243.
Onthenextpage, youwill writethefollowing 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) Assumethatwe wanttotestencode_word. Describethreetestcases
that each test different "categories" ofinputs. To describe each test case, give
thestrthatyouwould passtoencode_word, thereturnvalueyouexpect, and
thepurposeofthetestcase. Donotwriteanycode. Onthenextpage,wehave
given youonetestcaseasanexample; addthreemoreinthattable.
Page14 of22
.
CSC108H5F FinalExamination 2012 FallTerm
I Value ofword I Returnvalue IPurposeofthis test case
"zelda" 'z243' noduplicates
(b) (5 pOints) Now write function encode_word. Don't worry about copying the
docstring. You may assume the existence offunction letter_encoding that
takes a letter and returns its numeric encoding as a string. For example,
letter_encoding('a') returns '0'becausetheencodingfor a isO.
def encode_word(word):
Page15 of22
.
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
I
CSC108H5F FinalExamination 2012 FallTerm
8. (8 points) Majority rule is a voting system where a candidate must obtain more
than halfofthevotes to bedeclared the winner. If there is no candidate with the
majorityofvotes,thenthereisnowinner. Likeplurality,ballotsaresingle-candidate.
However, majorityruleis not thesameasplurality; makesureyou understandwhy
beforecontinuing.
Writea function calledmajority..rulethattakes a list ofstrings (the ballots) and
returns the majority winner. If there is no majority winner, the function should
returnNone.
Inthisquestion, wearenotdealingwiththefourpartiesfrom assignment2. Thelist
ofstringscouldcontainanynumberofdifferent candidatenames.
Youmust includeall stepsofthedesignrecipe in your solution (Le., examples, con-
tract, header, description, body); you will lose the majority ofmarks ifyou write
only codeanddonotincludetherecipecomponents.
Page17of22
.
CSC108H5F FinalExamination 2012 FallTerm
9. (12 points)
Considerthefollowing 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):
"'Aplayer 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) Createa Ring object and make rlrefer to thatobject. Thering's
nameshouldbe "gasharing" anditsmanashouldbe50.
(b) (2 paints) Write a methodcall thatremoves one manafrom the ring referred
tobyr1.
Page18 of22
t
CSC108H5F FinalExamination 2012 Fall Term
(c) Write thefollowing newmethods for thePlayerclass.
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) IproposethatRingshouldinheritfrom Playerratherthanobject.
Is thisreasonable? Answeryesor noandprovidea one-sentenceexplanation.
Page 19of22
,.
CSC108H5F FinalExamination 2012 Fall Term
10. (10 paints)
Throughoutthisquestion, assumethatwe aresortinglistsintonon-descendingorder.
Donotguessontheyes/noquestions. Thereisaone-markdeductionfor incorrect
answersonyes/noquestions.
(a) Assumethatasortis beingperformedona listandthatwe arefocusedonthree
consecutivepasses (notnecessarilythefirstthree). Thecontentsofthelistafter
thefirst andthirdofthese passes are shown, butthecontents afterthesecond
pass are hidden.
[3, 4, 5, 15, 3, 18, 11, 6]
[***hidden]
[3,3,4,5,15,18.11,6]
i. (1 point) Couldwe bedoingselectionsort? Checkone. 0 Yes oNo
ii. (1 point) Couldwebedoinginsertionsort? Checkone. 0 Yes oNo
iii. (1 point) Couldwe bedoing bubblesort? Checkone. 0 Yes oNo
(b) (2 points) Give an example of a list for which insertion sort requires fewer
comparisonsthanselectionsort.
(c) (3 points) Here is an idea for a sort that is a variation ofselection sort. On
eachpass:
Findthesmallest andlargest values anywhereintheunsortedpart
Swap thesmallest value with theleftmost value inthe unsorted part, and
swapthelargest valuewiththerightmost valueintheunsortedpart
Sortthefollowing list usingthisidea. Clearlyshowthecontentsofthelist after
eachpass.
[11, 20, 1991, 4. 13, 1992]
(d) (2 points) Whichofthefollowingcharacterizestheruntimeof thesortdescribed
above? Checkone. 0 linear 0 quadratic 0 cubic
Page20 of22
CSC108H5F Final Examination 2012 FallTerm
Short Pythonfunction/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 startingwith 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 of24 '
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.

Вам также может понравиться