0% found this document useful (0 votes)
31 views13 pages

Quiz 2

This document contains an introduction to computer science quiz with 15 multiple choice questions and coding/short answer questions. It tests knowledge of operating systems, Python, data structures, algorithms and binary search trees. The student provides their name and student ID and answers each question with explanations for short answer questions and code to implement binary search tree and linked list functions.

Uploaded by

張亭瑄
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)
31 views13 pages

Quiz 2

This document contains an introduction to computer science quiz with 15 multiple choice questions and coding/short answer questions. It tests knowledge of operating systems, Python, data structures, algorithms and binary search trees. The student provides their name and student ID and answers each question with explanations for short answer questions and code to implement binary search tree and linked list functions.

Uploaded by

張亭瑄
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
You are on page 1/ 13

Introduction to Computer Science Quiz 2

Student ID: B112045017

Name: 張亭瑄

A. Single Choice Questions (3%, 45%)


(1) Which of the following is not a role of a typical operating system?
(A) Control the allocation of the computer's resources
(B) Control access to the computer's input/output devices
(C) Maintain records regarding files stored in mass storage
(D) Assist the computer user in the task of processing digital photographs
Ans: (D)

(2) Which of the following statement is NOT true?


(A) In the partitioning scheme, the size of the partitions has to be determined beforehand
by the memory manager and the program has to be contiguous in memory.
(B) In paging scheme, both the memory and program are divided into equally sized
sections and the program does not have to be contiguous in memory.
(C) In demand segmentation scheme, the program and the memory segment are divided
into variable-size segments that match the programmer’s view.
(D) Virtual memory is used in both demand paging and demand segmentation scheme so
that when a program is being executed, part of the program is in memory and part is on
disk.
Ans: (C)

(3) Which of the following statement is true?


(A) Deadlock will always happen when the operating system puts too many resource
restrictions on a process.
(B) A process in the computer may be waiting for CPU time or executing. However, as long
as the job is in memory, it is regarded as a process.
(C) A program becomes a job from the moment it is selected for execution. Once it becomes
a job, it will be immediately loaded into the memory and stay there until it has finished.
(D) The process manager will store the entire job or process in the queue so that it can
handle multiple processes and jobs that request the same resources.
Ans: (B)

(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)

(5) Which one is NOT a correct way to create a list in Python


(A) x = []
(B) x = list()
(C) x = ()
(D) x = [0]
Ans: (C)

(6) Which of the following statement is NOT true?


(A) In Python, both the key and value of the dictionary are mutable.
(B) In Python, two items with the same value are allowed in a list.
(C) In Python, strings are more limited than other containers because only characters can
be stored in the string.
(D) In the high-level language, the source program must be translated to an object program
before execution on the target machine.
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)

(9) Which of the following statement is true?


(A) Both the sequential search and binary search algorithms can be directly applied to an
unsorted list.
(B) Iterative is a way of solving a problem using an algorithm that calls itself.
(C) For a list of n elements, both insertion sort and selection sort need n-1 pass to
rearrange the data completely.
(D) A program that never terminates can be considered as one type of algorithm.
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)

(11) Which of the following statement is NOT true?


(A) Insertion and deletion in a linked list are much easier than in an array since the
computer can spread the nodes through the whole memory.
(B) Arrays allow random access since the computer will store them in a contiguous
memory location.
(C) The elements in a record can be of the same or different types, but generally, all
elements in the record will be related.
(D) When applying the sequential search algorithm to a sorted linked list, both the cur and
pre pointer points to the node that holds the target value if the target is found.

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)

(15) Which of the following statement is true?


(A) Stack is a first in, first out (FIFO) structure.
(B) In Python, a list is an efficient way to implement a Queue.
(C) Tree defines a hierarchical structure in which a node can have only one single parent,
each node in a graph, on the other hand, can have one or more parents.
(D) A property of a binary search tree is that if we apply the preorder traversal of a binary
tree, the visited elements are sorted in ascending order.
Ans: (B)

B. Short-answer and coding questions


(16) What is the main difference between data structure and abstract data type? (5%)
Ans: Data structure is the way you can store the data to provide efficient ways to
operate on it. Data type is kind of instruction to computer language that tells how
to operate with data of this type.

(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

# Only left child.


if self.right is None:
lines, n, p, x = self.left._display_aux()
s = '%s' % self.data
u = len(s)
first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s
second_line = x * ' ' + '/' + (n - x - 1 + u) * ' '
shifted_lines = [line + u * ' ' for line in lines]
return [first_line, second_line] + shifted_lines, n + u, p + 2,
n + u // 2
# Only right child.
if self.left is None:
lines, n, p, x = self.right._display_aux()
s = '%s' % self.data
u = len(s)
first_line = s + x * '_' + (n - x) * ' '
second_line = (u + x) * ' ' + '\\' + (n - x - 1) * ' '
shifted_lines = [u * ' ' + line for line in lines]
return [first_line, second_line] + shifted_lines, n + u, p + 2,
u // 2

# 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

def create_tree(root,val): # create a binary tree


newnode = tree()
newnode.data = val
newnode.left = None
newnode.right = None
if root == None:
root = newnode
return root
else:
current = root
while current != None:
backup = current
if current.data > val:
current = current.left
else:
current = current.right
if backup.data > val:
backup.left = newnode
else:
backup.right = newnode
return root
data=[17,6,3,14,19,5,11,22,18,30]
ptr = None
root = None
for i in range(len(data)):
ptr=create_tree(ptr,data[i])

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

(18) The linked list in our slide is defined as follows: (6%)


class LinkedList:
def __init__(self, nodes=None):
self.head = None
if nodes:
node = Node(data=nodes.pop(0)) #pop will pop out the first entry
of the list
self.head = node
for elem in nodes:
node.link = Node(data=elem)
node = node.link
def __repr__(self): #This is to beautify printing, don't worry about
this
node = self.head
nodes = []
while node is not None:
nodes.append(str(node.data))
node = node.link
nodes.append("None")
return " -> ".join(nodes)

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')

[{'name': 'allen', 'score': 90},


{'name': 'bob', 'score': 100},
{'name': 'cathy', 'score': 85},
{'name': 'david', 'score': 80}]
bubble_sort(grades, key='score', descending=True)

[{'name': 'david', 'score': 80},


{'name': 'cathy', 'score': 85},
{'name': 'allen', 'score': 90},
{'name': 'bob', 'score': 100}]

(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

# Your code here


sum=0
i=0
counter = 1
for i in range(2, 51, 2):
sum = i+sum
if counter %5 == 0:
print(sum)
counter = counter+1

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

Ans: Yes, since X always larger than 0 , it forms an infinite loop.

(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 ]

You might also like