Quiz 2
Quiz 2
Name: 張亭瑄
(4) Which of the following statement will produce different results than the other three in a
for loop in Python?
(A) range(0, 9)
(B) range(0, 10, 1)
(C) range(0, 10)
(D) range(10)
Ans: (A)
(7) When using the binary search for entry 19 within the following list, how many entries will
be considered before discovering that the entry is not present?
[1,5,9,15,21,25,29]
(A) 7
(B) 6
(C) 4
(D) 3
Ans: (D)
(8) Which of the following lists would not be obtained at some point when applying the
selection sort algorithm to the list below?
[4,2,1,1,2,4,2]
(A) [1,2,4,1,2,4,2]
(B) [1,1,2,4,2,4,2]
(C) [2,4,1,1,2,4,2]
(D) [1,1,2,2,4,4,2]
Ans: (C)
(10) If the two-dimensional array X were stored in column-major order, then in the block of
main memory containing X, which of the following would be true?
(A) The entry X[1,2] would appear before X[2,1].
(B) The entry X[3,3] would appear before X[2,4].
(C) The entry X[3,2] would appear after X[2,3].
(D) The entry X[1,2] would be in the same location as X[2,1].
Ans: (B)
Ans: (D)
(12) Suppose you were going to retrieve items of data that you would later need to process in
the same order in which they were retrieved. Which of the following would be the best
structure to store the items?
(A) Queue
(B) Stack
(C) Binary search tree
(D) Graph
Ans: (A)
(13) Which of the following tree have a different root than the other tree?
(A) Tree with postorder traversal: FCBDG
(B) Tree with preorder traversal: GBCDAI
(C) Tree with postorder traversal: DCGBA
(D) Tree with preorder traversal: GBAID
Ans: (C)
(14) What is the total number of nodes you visit when you search 14 in the following binary
search tree?
17
/ \
6 19
/ \
3 14
(A) 2
(B) 3
(C) 4
(D) 5
Ans: (B)
(17) The binary search tree in our slide is defined as follows: (8%)
class tree:
def __init__(self):
self.data = 0
self.left = None
self.right = None
def __repr__(self):
lines, *_ = self._display_aux()
return "\n".join(lines)
def _display_aux(self):
# https://stackoverflow.com/questions/34012886/print-binary-tree-
level-by-level-in-python
"""Returns list of strings, width, height, and horizontal
coordinate of the root."""
# No child.
if self.right is None and self.left is None:
line = '%s' % self.data
width = len(line)
height = 1
middle = width // 2
return [line], width, height, middle
# Two children.
left, n, p, x = self.left._display_aux()
right, m, q, y = self.right._display_aux()
s = '%s' % self.data
u = len(s)
first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s + y * '_' + (m
- y) * ' '
second_line = x * ' ' + '/' + (n - x - 1 + u + y) * ' ' + '\\' +
(m - y - 1) * ' '
if p < q:
left += [n * ' '] * (q - p)
elif q < p:
right += [m * ' '] * (p - q)
zipped_lines = zip(left, right)
lines = [first_line, second_line] + [a + u * ' ' + b for a, b in
zipped_lines]
return lines, n + m + u, max(p, q) + 2, n + u // 2
ptr
____17___
/ \
_6___ 19_
/ \ / \
3 14 18 22_
\ / \
5 11 30
Complete the following function so that it will return the total number of nodes it visits
when the algorithm stops. Note your code should pass the following test data.
Hint: You can modify the search algorithm in our slide
def search(ptr,target):
"""
Parameters
----------
ptr: tree
The input binary search tree
target: int
The target value.
Returns
-------
count: int
Total number of nodes that have been visit
"""
# Your code here
count = 1
cur = ptr.data
while cur != None:
if cur > target:
ptr = ptr.left
cur = ptr.data
count = count+1
if cur < target:
ptr = ptr.right
cur = ptr.data
count = count+1
if cur == target:
return count
# Test data
assert search(ptr,11) == 4
assert search(ptr,22) == 3
assert search(ptr,30) == 4
class Node:
def __init__(self, data):
self.data = data
self.link = None
def __repr__(self):
return str(self.data)
Complete the following function so that it will return the geometric mean of the positive
numbers in the linked list. Note your code should pass the following test data.
Hint: You can use the traversal algorithm in our slide
def LinkedListGeoM(ilist):
"""
Parameters
----------
ilist: llist
The input list that contains positive numbers.
Returns
-------
geom : int
The geometric mean of the elements inside the linked list
"""
# Your code here
count = 1
pre = None
cur = ilist.head
result = cur.data
while cur != None and cur.link != None:
pre = cur
result = cur.link.data *result
cur = pre.link
count = count+1
geom = result**(1/count)
return geom
return geom
# Test data
from scipy.stats import gmean
ilist1 = LinkedList([102,132,178,201])
ilist2 = LinkedList([3,3,3,3,3])
ilist3 = LinkedList([1,20,78,22,13,80])
assert(int(LinkedListGeoM(ilist1)) == int(gmean([102,132,178,201])))
assert(int(LinkedListGeoM(ilist2)) == int(gmean([3,3,3,3,3])))
assert(int(LinkedListGeoM(ilist3)) == int(gmean([1,20,78,22,13,80])))
(19) The following program segment is designed to calculate the combination of n objects
taken k at a time using recursion. (6%)
C ( n , k )=
{C ( n −1 , k ) 1+Cif (k=0 or n=k
n −1 , k −1 ) otherwise
import math as m
def comb_r(n, k):
if k == 0 or k == n:
return 1
else:
return m.comb(n-1, k-1) + m.comb(n-1, k)
Modify the above program to calculate combination using a loop by completing the
following function. Note your code should pass the following test data.
def comb_i(n, k):
"""
Parameters
----------
n: int
Number of objects
k: int
Taken times
Returns
-------
combubation : int
the combination of n objects taken k at a time using
recursion.
"""
# Your code here
stack = []
stack.append((n, k))
combination = 0
while len(stack):
n, k = stack.pop()
if k == 0:
combination += 1
elif n<k:
combination += 0
else:
stack.append((n-1, k))
stack.append((n-1, k-1))
return combination
# Test data
from math import comb
assert(comb_i(5,3)==comb(5,3))
assert(comb_i(7,2)==comb(7,2))
assert(comb_i(6,6)==comb(6,6))
(20) Modify the bubble sort program in our slides to sort the following list of scores. (8%)
grades = [
{ 'name': 'david', 'score': 80},
{ 'name': 'allen', 'score': 90},
{ 'name': 'bob', 'score': 100},
{ 'name': 'cathy', 'score': 85}
]
Your bubble_sort function should take a key from grades and sort the list as per that key.
For example,
bubble_sort(grades, key='score', descending=True)
should output
[
{'name': 'bob', 'score': 100},
{'name': 'allen', 'score': 90},
{'name': 'cathy', 'score': 85},
{'name': 'david', 'score': 80}
]
while
bubble_sort(grades, key='name')
should output
[
{ 'name': 'allen', 'score': 90},
{ 'name': 'bob', 'score': 100},
{ 'name': 'cathy', 'score': 85},
{ 'name': 'david', 'score': 80}
]
Notice that you should complete the following function and produce the above results.
Hint: The string can be sorted as an integer using < or > operator since Python will
compare their ASCII code! You can access the score/name using grades[idx][score] or
grades[idx][name]. In addition, you can use the built-in function when reversing the
elements.
def bubble_sort(arr, key, descending=False):
"""
Parameters
----------
arr: list of dictionaries
The unsorted input list of dictionaries
key: str
Sort the data according to this key
descending: bool
If set to True, the output should be in descending order
Returns
-------
arr : list of dictionaries
The sorted list of dictionaries
"""
# Your code here
n=len(arr)
for i in range(n):
for j in range(0, n-1-i):
if arr[j][key]>arr[j+1][key]:
arr[j], arr[j+1]=arr[j+1], arr[j]
return arr
grades = [
{ 'name': 'david', 'score': 80},
{ 'name': 'allen', 'score': 90},
{ 'name': 'bob', 'score': 100},
{ 'name': 'cathy', 'score': 85}
]
bubble_sort(grades, key='name')
(21) The following code calculates 2+4+...+50 using loops and prints the intermediate results
every five iterations. Try to change the loop using for statement. (6%)
Hint: You can specify the step in the range function range(start, stop, step=1) and
you may find enumerate helpful in this problem.
sum = 0
i = 2
counter = 1
while i <= 50:
sum +=i
if counter %5 == 0:
print(sum)
counter = counter+1
i = i+2
30
110
240
420
650
30
110
240
420
650
(22) We have stored the two-dimensional array of students in the memory. The array is 100 ×
4 (100 rows and 4 columns). Show the address of the element students[7][2] assuming
that the element student[0][0] is stored in the memory location with address 10 and each
element occupies only one memory location. The computer uses row-major storage. (4%)
Ans: y=10+ 4 × 7+2=40
(23) A multi-programming operating system uses paging. The available memory is 100 MB
divided into 20 frames, each of 5 MB. The first program needs 13 MB. The second program
requires 12 MB. The third program requires 27 MB. (4%)
a. How many frames are used by the first program?
b. How many frames are unused?
Ans:
a. 3 frames.
b. 1.6 frames.
(24) A requirement of the algorithm is that it must terminate in a finite time. If the following
numeric values X are represented in two’s complement in our computer, do the following
program forms an infinite loop? Explain your answer. (4%)
X = 2
while (X > 0):
X = X + 1
(25) Assuming that we have a stack S that implements the four operations defined in stack
ADT. What will be the content of the stack after the following operation and why? Notice that
you should highlight which element is the topmost. (4%)
S = stack()
push(S,10)
push(S,5)
if (noy empty(S)) pop(S)
push(S,12)
push(S,7)
pop(S)
Ans: First we added 2 elements 10 and then 5 in S, since S is not empty, poped out
the topmost element 5.
Second we pushed 12 and then 7 in S, poped out the topmost element 7 .
Therefore the content of stack: [ 10 ,12 ]