0% found this document useful (0 votes)
17 views18 pages

Cs1010e 20222023 s2 Final Paper Questions

Uploaded by

xuweizheng45
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)
17 views18 pages

Cs1010e 20222023 s2 Final Paper Questions

Uploaded by

xuweizheng45
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/ 18

lOMoARcPSD|51007685

CS1010E 2022/2023 S2 Final Paper Questions

Programming Methodology (National University of Singapore)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Peijun Sun ([email protected])
lOMoARcPSD|51007685

CS1010E

NATIONAL UNIVERSITY OF SINGAPORE

CS1010E – PROGRAMMING METHODOLOGY


(Semester 2: AY2022/23)

Time allowed: 120 minutes

INSTRUCTIONS TO CANDIDATES

1. This assessment paper contains 32 questions and 17 pages including this cover page.

2. The maximum possible mark is 100.

3. This is an OPEN BOOK assessment. You may bring in any printed materials.

4. Answer all the questions using the knowledge you have learnt in CS1010E.

5. You may want to use the calculator embedded in Examplify.

6. You may assume that all relevant Python libraries (modules) have been imported.

7. Leave your student card on the desk throughout this assessment.

8. Do NOT look at the questions until you are told to do so.

=============================================================================
For examiner used only

Question numbers Possible marks Marks Remarks

MCQ (1-15) 30

Short Q (16 – 25) 40

Fill in the blank 30

Total 100

- 1 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

SECTION I. Multiple Choice Questions MCQ (30 marks)


1. What is printed by the following program?
a = 5 // -2
b = int( float('3.5') )
print(a, b)

A. -3 2
B. -3 3
C. -2 2
D. -2 3
E. An error will be reported.

2. What is printed by the following program?


lst1 = [2, 3, 4]
lst2 = lst1[1:]
lst1 = [5] + lst1
lst2[1] = 1
lst1[-1] = -1
print(sum(lst1), sum(lst2))

A. 5 5
B. 7 7
C. 9 4
D. 13 2
E. None of the above

- 2 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

3. Consider the following dictionary d


d = {
3: 'abc',
'a': 3,
'2': {2: 'abd', 'd': 3}
}
Which of the following expressions is evaluated to True?
A. d[3] > d['2'][2]
B. d['a'] == d['2']['d']
C. d['d'] == 3
D. 2 in d
E. None of the above

4. Suppose a text file “numbers.txt” contains the following values (where each value is on a line):

1
-2
5
0
3

What is printed by the following program?


file = open('numbers.txt', 'r')
line = file.readline()
c = 0
while line != '':
if int(line) <= 0:
c = c + 1
line = file.readline()
print(c)

A. -2
B. 0
C. 2
D. 5
E. None of the above

- 3 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

5. The Collatz conjecture states that given a positive integer 𝑛, if it is odd we multiply it by 3 and
add 1, or if it is even we divide it by 2. If we repeat this process, 𝑛 will eventually reach 1 where
the process stops. The number of steps taken for 𝑛 to reach 1 is called the cycle-length of n. By
definition, the cycle-length of 1 is 0.
E.g. given 𝑛 = 6, the sequence obtained is: 6  3  10  5  16  8  4  2  1
and the cycle-length of 6 is thus 8.
Which of the following is/are the correct implementation(s) of the function
count_cycle_length(n)?
(i) def count_cycle_length(n):
rounds = 0
while n > 1:
rounds = rounds + 1
if n%2 == 1:
n = 3*n +1
else:
n = n // 2
return rounds

(ii) def count_cycle_length(n):


rounds = 0
while True:
if n == 1:
return rounds
elif n%2 == 1:
n = 3*n +1
else:
n = n // 2
rounds = rounds + 1

(iii) def count_cycle_length(n):


if n == 1:
return 0
elif n%2 == 0:
return 1 + count_cycle_length(n//2)
else:
return 1 + count_cycle_length(3*n+1)
A. (i) only
B. (iii) only
C. (i) and (ii) only
D. (i), (ii) and (iii)
E. None of the above

- 4 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

6. Given a list of integers, the function rearrange(lt) rearranges all the integers in lt
such that,
 All negative integers (if any) move to the front of the list.
 All positive integers (if any) move to the back of the list.
 Zeroes (if any) should be placed between negative and positive integers.
 Relative order of negative and positive integers must be preserved. For example, if
a negative integer 𝑥 initially appears before another negative integer 𝑦, after re-
organizing, 𝑥 should still be in front of 𝑦.
A few examples are shown below:
 List [1, -2, 3, -4] will be rearranged as [-2, -4, 1, 3].
 List [-1, 9, -4, 0] will be rearranged as [-1, -4, 0, 9].
 List [0, -5, 7, 0, 3, -5] will be rearranged as [-5, -5, 0, 0, 7, 3].
The function rearrange(lt) is shown below, but line 6 is partially hidden from you
(hidden part is shown as XXXXXXXXXXXXX).
def rearrange(lt):
done = False
while not done:
done = True
for i in range(len(lst)-1):
if XXXXXXXXXXXXX: # line 6
lt[i], lt[i+1] = lt[i+1], lt[i]
done = False

Which of the following expressions can be substituted into the hidden part of line 6 to
produce the desired result?
A. (lt[i]>0 and lt[i+1]<0) or (lt[i]==0 and lt[i+1]<0)
B. (lt[i]>0 and lt[i+1]<=0) or (lt[i]==0 and lt[i+1]<0)
C. (lt[i]>0 or lt[i+1]<0) and (lt[i]==0 or lt[i+1]<0)
D. (lt[i]>0 or lt[i+1]<=0) and (lt[i]==0 or lt[i+1]<0)
E. None of the above

- 5 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

7. A geometric series is a series of non-zero numbers of the form a, ar, ar2, ar3, ar4 …. where a is
the initial value or the 1st term in the series and r is a non-zero number called the ratio of the
series.
You want to write a recursive function ngeoterm(a,r,n) to output the nth term in a geometric
series, with a being the 1st term in the series and r being the ratio.

Select the correct recurrence relation for ngeoterm(a,r,n) from the options below. You may
assume that a,r and n passed to ngeoterm is always valid.

Note that ^ in the options below means power. That is, x^y means xy.

A. ngeoterm(a,r,n) = a*r^n

B. ngeoterm(a,r,n) = a if n == 1
ngeoterm(a,r,n) = a*r^n if n > 1

C. ngeoterm(a,r,n) = 1 if n == 1
ngeoterm(a,r,n) = r*ngeoterm(a,r,n-1) if n > 1

D. ngeoterm(a,r,n) = a if n == 1
ngeoterm(a,r,n) = r*ngeoterm(a,r,n-1) if n > 1

E. ngeoterm(a,r,n) = a if n == 0
ngeoterm(a,r,n) = r*ngeoterm(a,r,n-1) if n > 0

- 6 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

8. Given any integer Z, Z can possibly be formed from the multiplication of 2 integers X and Y
where X and Y can be from the range 1 to Z (1 and Z inclusive).

For example, if Z = 30 then Z can be formed from the multiplication of 1*30, 2*15, 3*10,
5*6. Thus there are 4 unique ways to form Z from the multiplication of 2 integers from the
range 1 to 30.

Another example is when Z = 7. Here Z can only be formed from the multiplication of 1*7.
Thus there is one unique way to form Z from the multiplication of 2 integers from the
range 1 to 7.

You want to write a recursive function numwaytomul(Z,X,Y) which will take in the number Z
as a parameter and 2 other integers X and Y, and which will return the unique number of ways
to form Z from the multiplication of 2 integers in the range 1 to Z when you call
numwaytomul(Z,1,Z).

Select the correct recurrence relation for numwaytomul(Z,X,Y) from the options below.

A. numwaytomul(Z,X,Y) = 0 if X > Y
numwaytomul(Z,X,Y) = 1+numwaytomul(Z,X+1,Y-1) if X*Y == Z and X <= Y
numwaytomul(Z,X,Y) = numwaytomul(Z,X+1,Y-1) if X*Y != Z and X <= Y

B. numwaytomul(Z,X,Y) = 1 if X == Z or Y == 1
numwaytomul(Z,X,Y) = numwaytomul(Z,X+1,Y) +
numwaytomul(Z,X,Y-1) if X < Z and Y > 1

C. numwaytomul(Z,X,Y) = 0 if X > Y
numwaytomul(Z,X,Y) = 1 + numwaytomul(Z,X+1,Y-1) if X*Y == Z and X <= Y
numwaytomul(Z,X,Y) = numwaytomul(Z,X,Y-1) if X*Y != Z and Z%X == 0 and X <= Y

D. numwaytomul(Z,X,Y) = 1 if X > Y
numwaytomul(Z,X,Y) = 1 + numwaytomul(Z,X+1,Y-1) if X*Y == Z and X <= Y
numwaytomul(Z,X,Y) = numwaytomul(Z,X,Y-1) if X*Y != Z and Z%X == 0 and X <= Y
numwaytomul(Z,X,Y) = numwaytomul(Z,X+1,Y-1) if X*Y != Z and Z%X != 0 and X <= Y

E. numwaytomul(Z,X,Y) = 0 if X > Y
numwaytomul(Z,X,Y) = 1 + numwaytomul(Z,X+1,Y-1) if X*Y == Z and X <= Y
numwaytomul(Z,X,Y) = numwaytomul(Z,X,Y-1) if X*Y != Z and Z%X == 0 and X <= Y
numwaytomul(Z,X,Y) = numwaytomul(Z,X+1,Y-1) if X*Y != Z and Z%X != 0 and X <= Y

- 7 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

9. Your friend John has written the following Python function indexMin(lst,index) which will take
in lst (a list of possibly repeating integers), and index (an integer value) as parameters.

def indexMin(lst,index): # line 1


if index == len(lst)-1: # line 2
return index # line 3
else: # line 4
x = indexMin(lst,index+1) # line 5
if lst[index] < lst[x]: # line 6
return index # line 7
return x # line 8

John claims that calling indexMin(lst,0) when lst is non-empty will result in the index
of the first occurrence of the smallest integer value in lst to be returned.
Note that the first occurrence of an integer in lst is the leftmost occurrence of the integer in
lst.

Select all statement(s) which is/are true.

A. John is correct.
B. John is wrong. It does not work because line 2 is not correct
C. John is wrong. It does not work because line 3 is not correct
D. John is wrong. It does not work because line 5 is not correct
E. John is wrong. It does not work because line 6 is not correct
F. John is wrong. It does not work because line 7 is not correct
G. John is wrong. It does not work because line 8 is not correct

10. Select all statements that are true about searching and sorting from the options below:
A. Binary search and linear search will always work correctly on an unsorted list.
B. Binary search will always work correctly on a sorted list
C. For Binary search that makes use of 2 indices start and end to keep track of the start
and end index of the sub-lists, we can conclude the value to be search for is not in the
list only when start == end
D. Both Binary search and Merge sort is a divide-and-conquer strategy.

- 8 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

11. You are given the function DoSomething(L) where the parameter L is a 3-D array that is a
list of lists of lists.

def DoSomething(L):
x = len(L)
y = len(L[0])
res = []
if x == y :
for i in range(x):
res.append(list())
for j in range(y):
res[i].append(L[j][i])
return res
What is the content of the 3-D array res returned when DoSomething(L) is called for the
following L?

L = [[[0,1,2], [3,4,5], [6,7,8]],


[[9,10,11], [12,13,14], [15,16,17]]]

A. [[[0,1,2], [9,10,11]],
[[3,4,5], [12,13,14]],
[[6,7,8], [15,16,17]]]

B. [[[9,10,11], [0,1,2]],
[[12,13,14], [3,4,5]],
[[15,16,17], [6,7,8]]]

C. [[[0,1,2], [3,4,5], [6,7,8]],


[[9,10,11], [12,13,14], [15,16,17]]]

D. []

E. [[[9,10,11], [12,13,14], [15,16,17]],


[[0,1,2], [3,4,5], [6,7,8]]]

- 9 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

12. Given the following function


def fold_left(fn, initial, seq):
if seq == ():
return initial
else:
return fn(fold_left(fn, initial, seq[:-1]), seq[-1])
and a seq = (2,3,4,5,6,8,9,12,15,18)

What is printed by
print(fold_left(lambda a, b: (b) if a == () else (a,b), (),
tuple(filter(lambda i : i%3 ==0 and i%2 == 0, p))))

A. (6, 12, 18)


B. ((6, 12), 18)
C. (6, (12, 18))
D. ((6, 12, 18))
E. None of the above

13. Given the following mystery function

def mystery(obj, seq):


if seq == ():
return 0
elif seq[0] is obj:
return 1 + mystery(obj,seq[1:])
elif type(seq[0]) == tuple:
return mystery(obj,seq[0]) + mystery(obj,seq[1:])
else:
return mystery(obj,seq[1:])

if seq = ((1,2),((3,4),(2,3),(1,2),((1,2),(2,3),(3,4))),(1,2)), what is printed by

print(mystery((1,2),seq))?

A. 2
B. 3
C. 4
D. 5
E. 6

- 10 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

14. What kind of error will be reported by Python when you the code to Python?

try:
fp = open(‘myfile.txt’)
line = fp.readline()
i = int(s.strip())
except (IOError, ValueError) as e:
print(“check if the file is read-only.”, e.errno)
except;
print(“unexpected error”)

A. Syntax error
B. Run time error
C. Logic error
D. Unexpected erroe
E. None of the above

- 11 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

SHORT QUESTIONS (40 marks)


Write down the output of the following programs.

16.
a = [1, 2, (3, (4,), 5), [6]]
print(a[2][-2][0])
# output:

17.
def f(n):
c = 0
while n > 0:
if n%10%2 != 0:
c = c + 1
n = n // 10
return c

print(f(2345678))
# output:

18.
lst1 = [0, 1, 2]
lst2 = [0, 1, 2]
lst3 = [[3, 4], 'abc', ((6,), 7)]
lst1.append(lst3)
lst2.extend(lst3)
print(len(lst2) - len(lst1))
# output:

19. Please omit opening and closing quotation marks in your answer.
def f(s):
res = '' # begin with an empty string
for char in s:
if char not in 'aeiou' and char not in 'AEIOU':
res = res + char
return res

print(f('Astonished'))
# output:

- 12 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

20.
Total = 0
For num in range(10):
if num % 2 == 0:
total = total + 2
elif num <= 3:
total = total - 2
else:
break
total = total + 1

print(total)
# output:
21.
t = (123456, 23456, 3456, 456, 56, 6)
def f():
largest = t[0]
for val in t:
if greater_than(val, largest):
largest = val
return largest

def greater_than(n1, n2):


while n1 >= 100:
n1 = n1 // 100
while n2 >= 100:
n2 = n2 // 100
return n1 > n2

print(f())
# output:
22.
def accumulate (fn, initial,seq):
if seq == ():
return initial
else:
return fn(seq[0],accumulate(fn,initial,seq[1:]))

k = (1, 2, 5, 3, 7, 9,4)
print(accumulate( lambda a, b: b if a >= b else a, 3, k))

# output:

- 13 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

23. You are given the following functions

def someRecFunc2(n):
if n == 1:
return n
else:
return n+someRecFunc1(-1*n)
def someRecFunc1(n):
if n <= 1:
return n
else:
return n+someRecFunc2(-1*(n-1))
What is the value returned when someRecFunc1(513) is called?
Ans:
24. What is the output of the following Python code?

def divisible_by_digits(start_num, end_num):


return [n for n in range(start_num, end_num+1) \
if not any(map(lambda x: int(x) == 0 \
or n%int(x) != 0,str(n)))]
print(divisible_by_digits(1,22))

Ans:
25. Given the following Python code, what will be the output?

class A: Ans:
def test(self):
print("test of A call")
class B(A):
def test(self):
print("test of B call")
super().test()
class C(A):
def test(self):
print("test of C call")
super().test()
class D(B):
def test2(self):
print("test of D call")
C().test()

D()test()

- 14 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

Question 26 to 28 refers to the problem described below: (12 marks)


Given L a list of integers, you want to shift all integers in the list to the right by m. If this exceeds
the maximum index of L you will simply wrap around to index 0 and continue shifting.
As an example:
Given L = [0,1,2,3,4], m = 1, you will end up with L = [4,0,1,2,3] after shifting all integers to the
right by 1.
Given L = [0,1,2,3,4], m = 3, you will end up with L = [2,3,4,0,1] after shifting all integers to the
right by 1.

You are given the incomplete function rightShift(L,m,n) below, which will shift all integers
in L to the right m as described above and return this modified L (instead of a new list). The
parameter n is always the length of L. Complete it by selecting the most appropriate code to
replace each of the “<blank X>” where X is a number.
def shiftRight(L,m,n):
if n == <blank 1>:
return
else:
x = L[n-1]
<blank 2>
shiftRight(L,m,n-1)
<blank 3>

26. <blank 1> should be replaced by:


Ans:

27. <blank 2> should be replaced by (if you think there should be no statement here, type in
"Empty" without the "" in the textbox):
Ans:

28. <blank 3> should be replaced by (if you think there should be no statement here, type in
"Empty" without the "" in the textbox):
Ans:

- 15 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

29. You are supposed to write a Python program to find palindromes in a given list
of strings using Lambda. (4 marks)

A palindromic number or numeral palindrome is a number that remains the


same when its digits are reversed. Like 16461, for example, it is "symmetrical".
The term palindromic is derived from palindrome, which refers to a word (such
as rotor or racecar) whose spelling is unchanged when its letters are reversed.
The first 30 palindromic numbers (in decimal) are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11,
22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191,
202.

You may like to know that “”.join(reversed(‘abc’)) produces ‘cba’


texts = ["php", "w3r", "Python", "abcd", "Java", "aaa"]
result = list( statement to achieve the result )
print(result)

Replace the “statement to achieve the result” with the appropriate


statement so that you can find all the palindromes from the given
input.

For example, the result printed should be [“php”,”aaa”]

Ans:

Question 30 to 32 is based on the following OOP classes (12 marks)


class Shape:
def __init__(<< Q30: write the appropriate parameter>>):
<< Q31: write appropriate statements
to initialise the attributes>>

def whatShape(self):
<< Q32:write appropriate statements
to achieve the required result>>

class Rectangle(Shape):
def __init__(self, length, width):
super().__init__("Square",length, width)

class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle",radius)

class Triangle(Shape):
def __init__(self, side1, side2, side3):
super().__init__("Triangle",side1,side2,side3)

- 16 of 17 -

Downloaded by Peijun Sun ([email protected])


lOMoARcPSD|51007685

CS1010E

The following is a sample run:

S1 = Rectangle(4,5)
S2 = Circle(6)
S3 = Triangle(7,8,9)

print(S1.whatShape())
I am a Rectangle with length 4 and width 5

print(S2.whatShape())
I am a Circle with radius 6

print(S3.whatShape())
I am a Triangle with side1 7 side2 8 and side3 9

Q30 Write the parameter for the class Shape

Ans:

Q31 Write the statements of the constructor of class Shape

Ans:

Q32 Write the statement for the method whatShape() so that the
appropriate message can be printed.

Ans:

=== END OF PAPER ===

- 17 of 17 -

Downloaded by Peijun Sun ([email protected])

You might also like