Vous êtes sur la page 1sur 7

QUIZ

Q1 What does f(1782818) return, for the following function definition:

def f(x):
d=0
while x > 1:
(d,x) = (d+1,x/10)
return(d)

Solution: Correct answer: 7


The loop counts the number of digits in x. The number of digits is the number of times you can divide x by
10 before the value goes below 1.

Q2 What is the value of h(5,4) for the function below?

def h(m,n):
ans = 1
while (n > 0):
(ans,n) = (ans*m,n-1)
return(ans)

Solution: Correct answer: 625


The function computes m**n by repeatedly multiplying m by itself n times. 5**4 is 625.

Q3 What can we say about a number n if g(n) returns True for the function g given below?

def g(n):
for i in range(2,n):
if n%i == 0:
return(False)

return(True)

n is a prime number.

n is a composite number.

n is multiple of 2.

None of the above.

Intended answer: (a) n is a prime number


The loop returns False if a divisor is found between 2 and n-1. If the loop exits, there are no divisors of n
other than 1 and n, so n is a prime.
However, there is a bug in the code, so g(1) also returns True, though 1 is not a prime. Hence (d) None
of the above will also be accepted as a correct answer.
Q4 What would happen if we call gcd(m,n) with m positive and n negative in the following definition?

def gcd(m,n):

if m < n:
(m,n) = (n,m)

if (m % n) == 0:
return(n)
else:
diff = m-n
return (gcd(max(n,diff),min(n,diff)))

The function would still compute gcd correctly.

The function would not terminate.

The behaviour depends on the exact values of m and n.

Correct answer: (c) The behaviour depends on the exact values of m and n
Try it out in the Python interpreter and see for yourself!

Q5 One of the following 10 statements generates an error. Which one? (Your answer should be a
number between 1 and 10.)

x = [1,"abcd",2,"efgh",[3,4]] # Statement 1
y = x[0:50] # Statement 2
z = y # Statement 3
w = x # Statement 4
x[1] = x[1] + 'd' # Statement 5
x[1][1] = 'y' # Statement 6
y[2] = 4 # Statement 7
z[0] = 0 # Statement 8
w[4][0] = 1000 # Statement 9
a = (x[4][1] == 4) # Statement 10

1 point

Correct answer: 6
Statement 6 is trying to update a position in a string. x[1] is "abcd" and x[1][1] is "b".

Q6 Consider the following lines of Python code.

x = [13,4,17,1000]
w = x[1:]
u = x[1:]
y = x
u[0] = 50
y[1] = 40

Which of the following is correct?


x[1] == 40, y[1] == 40, w[0] == 50, u[0] == 50

x[1] == 4, y[1] == 40, w[0] == 4, u[0] == 50

x[1] == 50, y[1] == 50, w[0] == 50, u[0] == 50

x[1] == 40, y[1] == 40, w[0] == 4, u[0] == 50

Correct answer: (d) x[1] == 40, y[1] == 40, w[0] == 4, u[0] == 50


x and y refer to the same list, while w and u are two independent slices. The update to u[0] does not affect
any of the other names. The update to y[1] is also reflected in x[1].

Q7 What is the value of endmsg after executing the following lines?

startmsg = "hello"
endmsg = ""
for i in range(0,len(startmsg)):
endmsg = startmsg[i] + endmsg

Correct answer: "olleh"


The loop reverses the string by inserting each letter in startmsg at the beginning of endmsg.

Q8 What is the value of mylist after the following lines are executed?

def mystery(l):
l = l + l
return()

mylist = [31,24,75]
mystery(mylist)

1 point

Correct answer: [31,24,75]


The update l = l + l inside the function creates a new list, so the list passed as the argument is not changed.

Q9 Consider the following Python function.

def mystery(l):
if l == []:
return (l)
else:
return (l[-1:] + mystery(l[:-1]))

What does mystery([3,2,7,8,5]) return?

Correct answer: [5,8,7,2,3]


The code reverses a list by putting the last element in front and inductively reversing the first n-1 elements.

Q10 What is the value of pairs after the following assignment?

pairs = [ (x,y) for x in range(4) for y in range(3) if (x+y)%2 != 0 ]

Correct answer: [(0,1),(1,0),(1,2),(2,1),(3,0),(3,2)]


Pick pairs (i,j) for 0 ≤ i ≤ 3, 0 ≤ j ≤ 2 such that i+j is odd.

Q11 Consider the following dictionary.

marks =
{"Quizzes":{"Mahesh":[3,5,7,8],"Suresh":[9,4,8,8],"Uma":[9,9,7,6]},"Exams":{"Ma
hesh":[37],"Uma":[36]}}

Which of the following statements does not generate an error?

marks["Exams"]["Suresh"].extend([44])

marks["Exams"]["Suresh"].append(44)

marks["Exams"]["Suresh"] = [44]

marks["Exams"]["Suresh"][0:] = [44]

Correct answer: (c) marks["Exams"]["Suresh"] = [44]


Direct assignment to a new key adds a value. All other updates result in KeyError.

Q12 Assume that d has been initialized as an empty dictionary:

d = {}

Which of the following generates an error?

d[[1,2]] = 5

d[(1,2)] = 5

d["1,2"] = 5

d[12] = 5

Correct answer: (a) d[[1,2]] = 5


Key must be an immutable value. List is not OK. Tuple, string and integer are OK.
Q13 Suppose u and v both denote sets in Python. Under what condition can we guarantee that u - (u
- v) == v?

This is true for any u and v.

The set u should be a subset of the set v

The set v should be a subset of the set u

The sets u and v should be disjoint.

Correct answer: (c) The set v should be a subset of the set u


Follows from basic set theory. (u-v) is the complement of v with respect to u. u - (u-v) is the complement of
the complement. If v had any element not present in u, this element would not belong to u - (u-v). But if v is
a subset of u, the complement of the complement of v is v itself.

Q14 Suppose u and v both denote sets in Python. Under what condition can we guarantee that u|v ==
u^v?

This is true for any u and v.

The set u should be a subset of the set v

The set v should be a subset of the set u

The sets u and v should be disjoint.

Correct answer: (d) The sets u and v should be disjoint.


u|v represents the union of u and v. u^v is the set of elements in exactly one of u and v (xor). If there is
any element common to u and v, this element would belong to u|v but not u^v.

Q15 Suppose we insert 97 into the max heap [98,67,89,38,42,54,89,17,25]. What is the resulting heap?

1 point

Correct answer: [98,97,89,38,67,54,89,17,25,42]


97 is added as the left child of 42. It gets swapped with 42 and 67, the parent of 42.

Q16 Suppose we we apply delete_max() twice to the heap [100,97,93,38,67,54,93,17,25,42]. What is the
resulting heap?

1 point

Correct answer: [93,67,93,38,42,54,25,17]


The first delete_max results in [97,67,93,38,42,54,93,17,25]: 42 replaces 98 and gets swapped down with
97 and 67.
The second delete_max results in [93,67,93,38,42,54,25,17]: 25 replaces 97 and gets swapped with both
copies of 93.
Q17 Given the following permutation of a,b,c,d,e,f,g,h,i,j, what is the next permutation in
lexicographic (dictionary) order? Write your answer without any blank spaces between letters.

fjadbihgec

1 point

Correct answer: fjadcbeghi


Reading backwards, the ascending sequence in fjadbihgec ends at b. So we swap b with the next
largest letter to its right, c, and rearrange the sequence ihgeb in ascending order.

Q18 We want to add a function length() to the class Node that implements user defined lists which will
compute the length of a list. An incomplete implementation of length() given below. You have to provide
an expression to put in place of *** on the last line.
def length(self):
if self.value == None:
return(0)
elif self.next == None:
return(1)
else:
return(***)

1 point

Correct answer: 1+self.next.length(), or self.next.length()+1


Natural inductive definition: length is 1 for the first element plus, inductively, the length of the rest of the list.

1 point
Q19 Suppose we add this function foo() to the class Tree that implements search trees. For a
name mytree with a value of type Tree, what would mytree.foo() compute?
def foo(self):
if self.isempty():
return(0)
elif self.isleaf():
return(1)
else:
return(1 + max(self.left.foo(),self.right.foo()))

The number of nodes in mytree.

The largest value in mytree.

The length of the longest path from root to leaf in mytree.

The number of paths in mytree.

Correct answer: (c) The length of the longest path from root to leaf in mytree.
The height of a tree is the length of the longest path to a leaf. This is 1 plus the longest path in either the
left or the right subtree.

Inorder traversal of a binary tree has been defined in the lectures.

A preorder traversal lists the vertices of a binary tree (not necessarily a search tree) as follows:

 Print the root.


 Print the left subtree in preorder.
 Print the right subtree in preorder.

Q20 Suppose we have a binary tree with 10 nodes labelled a, b, c, d, e, f, g, h, i, j, with


preorder traversal gbhecidajf and inorder traversal ehbicgjafd.

What is the left child of the root node?

Hint: The preorder traversal tells you the root of the tree. By locating the root in the inorder traversal, you
can identify the nodes in the left and right subtrees. In this way, you can recursively reconstruct the tree
from the two traversals.

1 point

Correct answer: b
From the preorder traversal, g is the root of the tree. From the inorder traversal, the nodes in the left
subtree are ehbic. Referring back to the preorder traversal, the root of this subtree is b.

Vous aimerez peut-être aussi