0% found this document useful (0 votes)
6 views9 pages

Test1 Practice

Uploaded by

G Jeffery
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views9 pages

Test1 Practice

Uploaded by

G Jeffery
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CSC 148H5 Y Practice Questions

Duration — 50 minutes
Aids allowed: none

This practice questions booklet consists of 6 questions on 9 pages (including # 1: / 2


this one).
# 2: / 2
• Remember that just doing these practice questions is not enough. e.g.
there isn’t much of a focus on OOP/class building/custom exceptions # 3: / 4
in this package, so you must do more practice alongside this. # 4: / 3
• In your responses, no error checking is required: assume all user input # 5: / 3
and all argument values are valid.
# 6: / 3
• Remember, on the test – if you use any space for rough work, indicate
clearly what you want marked.
TOTAL: /17

Total Pages = 9
Practice Questions

Question 1. [2 marks]
What is the output of the following code? Write your response in the box below.

def f(num, lst):


if (num == 0) or len(lst) == 0:
return lst
return [lst[0]*2] + f(num-1, lst[1:])

print(f(0, [1, 2, 3]))


print(f(2, []))
print(f(2, [1, 2, 3, 5, 6]))
print(f(5, [10, 11]))

Question 2. [2 marks]
For the function below, finish the type contract (the data type for the parameter and the return value)
and write a good docstring description explaining what the code does. You do NOT need to write the
examples. Just the type contract, and the description (not a line-by-line description of the code, but a
docstring-style general description) is needed.

def mystery(s):
‘‘‘
( ) ->

’’’

if s == ’’:
return s

new_s = ’’

try:
new_s = str(int(s[0]))
except:
new_s = ’*’

return new_s + mystery(s[1:])

Page 2 of 9
Practice Questions

Question 3. [4 marks]
On the right side of this page, write down the output of the following program as it would appear in the
console. If the program terminates with an exception that is not handled, write the word CRASH at the
end of your answer.

class A: # WRITE THE OUTPUT BELOW HERE:

def __init__(self, x):


self.x = x

def double_x(self):
self.x = self.x * 2

class B(A):

def __init__(self, y):


self.y = y

def double_y(self):
self.y = self.y * 2

class C(B):
pass

if __name__ == "__main__":
a = A(1)
b = B(2)
c = C(3)

try:
print("a.x =", a.x)
print("b.y =", b.y)
print("b.x =", b.x)
except:
print("bad!")

try:
b.double_y()
except IOError:
print("bad again!")
finally:
print("finally")

try:
print("final a =", a.x)
print("final b =", b.y)
print("final c =", c.y)
except:
print("still bad!")

print("It’s all good")

Page 3 of 9
Practice Questions

Question 4. [3 marks]
Complete the following function that operates on a stack. Assume that the push, pop, and is_empty
stack methods are available (details are in the API sheet). Do not call any method besides these three.
Complete this by filling in the blanks with appropriate code. Do not rewrite the function.

def duplicate_all(s: Stack) -> None:


’’’
Given a Stack s of integers, modify s to duplicate all elements in the stack,
so that each element appears twice in a row as shown in the example.

Do NOT return a new stack. Modify the one that is given.

>> s = Stack()
>> s.push(3)
>> s.push(2)
>> duplicate_all(s)
>> s.pop()
2
>> s.pop()
2
>> s.pop()
3
>> s.pop()
3
’’’

s2 = ______________________________

while _______________________:

elm = _____________________

s2.push(_______________)

_________________________

while not s2.is_empty():

__________________________

Page 4 of 9
Practice Questions

Question 5. [3 marks]
Complete the following function that operates on a stack. Assume that the push, pop, and is_empty
stack methods are available (details are in the API sheet). Do not call any method besides these three.
Complete this by filling in the blanks with appropriate code. Do not rewrite the function.

def remove_odd(s: Stack) -> None:


’’’
Given a Stack s of integers, modify s to remove any elements that are an odd number.

Do NOT return a new stack. Modify the one that is given.

>> s = Stack()
>> s.push(10)
>> s.push(3)
>> s.push(2)
>> s.push(9)
>> s.push(5)
>> remove_odd(s)
>> s.pop()
2
>> s.pop()
10
’’’

s2 = _____________________

while _______________________:

elm = s.pop()

if _________________________:

s2.push(____________________)

while _______________________:

s.push(__________________)

Page 5 of 9
Practice Questions

Question 6. [3 marks]
Read the code below and finish the type contract (the data type for the return value) and write a good
docstring description explaining what the function does. You do NOT need to write the examples. Just the
description (not a line-by-line description of the code, but a docstring-style general description) is needed.

def unravel(nested: list) -> ___________:


"""

"""

q = Queue()
for e in nested:
q.enqueue(e)

while not q.is_empty():


i = q.dequeue()
if not isinstance(i, list):
print(i)
else:
for e in i:
q.enqueue(e)

What would be the output of the code below, which uses the function above? Write the output in the
space below.

>>> L = [’a’, [’b’, [’c’, ’d’], ’e’, ’f’], [’g’, ’h’, ’i’], ’j’]
>>> unravel(L)

Page 6 of 9
Practice Questions

[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 7 of 9
Practice Questions

[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 8 of 9
Short Python function/method descriptions:
__builtins__:
int(x) -> int
Convert x to an integer, if possible. A floating point argument will be truncated towards zero.
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 sequence starts at 0. If step is not specified, the values are incremented by 1.
str(x) -> str
Return an object converted to its string representation, if possible.
isinstance(x, class) -> bool
Return True if <x> is an instance of the data type <class>, and False otherwise.
Stack:
is_empty(self)
Return whether this stack is empty.
pop(self)
Remove and return the top item. If stack is empty, raise EmptyStackError.
push(self, o)
Make o the new top item in this Stack.
Queue:
is_empty(self)
Return whether this queue is empty.
dequeue(self)
Remove and return the item at the front of this queue.
enqueue(self, o)
Add o to the back of this queue.
str:
x in s -> bool
Return True if and only if x is in s.
S.find(sub[,i]) -> int
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.isalpha() -> bool
Return True if and only if all characters in S are alphabetic
and there is at least one character in S.
S.isdigit() -> bool
Return True if and only if all characters in S are digits
and there is at least one character in S.
S.split([sep]) -> list of str
Return a list of the words in S; use string sep as the separator and
any whitespace string if sep is not specified.
list:
x in L --> bool
Return True if and only if x is in L
L.append(object) -> NoneType
Append object to end of L.
L.extend(iterable) -> NoneType
Extend list L by appending elements from the iterable. Strings and lists are
iterables whose elements are characters and list items respectively.
L.pop([index]) -> item
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
L.index(value, [start, [stop]]) -> integer
Return first index of value. Raises ValueError if the value is not present.

Total Pages = 9 End of Test

You might also like