[go: up one dir, main page]

0% found this document useful (0 votes)
4 views10 pages

COMP2101 Final SP24 (With Solution)

Uploaded by

jzwyp9rkcm
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)
4 views10 pages

COMP2101 Final SP24 (With Solution)

Uploaded by

jzwyp9rkcm
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/ 10

SULTAN QABOOS UNIVERSITY, COLLEGE OF SCIENCE

DEPARTMENT OF COMPUTER SCIENCE


COMP2101: INTRODUCTION TO COMPUTER SCIENCE
FINAL EXAM
SPRING 2024

WEDNESDAY 15TH MAY 2024 (15:00 - 17:30 PM)

TIME DURATION
2 Hours and 30 Minutes

FORM-A

NAME:___________________________________ ID #:___________________ Section: _________

GRADING TABLE

Question Mark

MCQ ______________ /10

True/False ______________ /10

Functions ______________ /14

List and Strings ______________ /10

Tables ______________ /6

Files ______________ /10

Total ______________ /60

Page 1 of 10
Question 1: [10 points] Multiple Choice Questions (1 point each)

1. A sequence of steps that solves a problem, and terminating is called ......................

a. Compiler b. Computer c. Programmer d. Algorithm

2. What is the output when the following code is run?

def power(x):
x = x**x
return
x=5
power(x)
print(x)

a. 25 b. 5 c. 5**5 d. Error

3. Which function call will cause Python to report an error?

a. round(1, d. abs(-1, -
2)
b. min(1, 2) c. max(1, 2)
2)

4. Does the following Python code calculate the average speed of a car that travels a distance of 150
kilometers in 3 hours?
distance_kilometers = 150
time_hours = 3
average_speed = distance_kilometers % time_hours
print("Average speed:", average_speed, "km/h")

a. Yes, it works as expected b. Code generates compilation error


c. Resulted output has logical error d. Code generates runtime error

Page 2 of 10
5. What exception will be raised by the following code?

string ='helo'
try:
print(string[10])
except __________________ as e:
print('Error', e)

a. ValueError b. IOError c. RuntimeError d. IndexError

6. How many iterations will the following for loop perform?


for i in range(1, 10, 2):
print(i)

a. 4 b. 5 c. 6 d. 10

Page 3 of 10
7. Which code matches this flowchart?

a. x = 12 b. x = 12
x = 12
while x<30: while x<30:
x += 10 x += 10
print(x) print(x)
c. x = 12 d. x = 12 x < 30 print(x)
if x<30: if x<30:
x += 10 x += 10
print(x) print(x)
x += 10

8. Which import statement correctly allows the execution of the following Python statement?
print(math.sqrt(25))

a. from math import sqrt b. from math import *


c. import math d. Import math.sqrt

9. What does the following code print?


my_string = "hello world"
result = my_string.split()
print(len(result))

a. 1 b. 2 c. 11 d. [‘hello’, ‘world’]

10. The act of implementing, and testing computer programs is called:


a. Programming b. Pseudocode c. Decomposition d. Flowchart

Page 4 of 10
Question 2: [10 points] True/False
State true/ false to the following questions (1 point each)
Note: Writing T or F considered as invalid and will be given zero to that answer.

Answer each of the following True/False

Comments in Python are always required and must be included for the
1. False
program to run correctly.

2. Strings are composed of only letters and numbers. False

The output of the following code will be: Yes


x = 20
y = False
3. if (not(x < 10*2) or y): True
print("Yes")
else:
print("No")

Global variables in Python can be accessed from any function within the
4. True
same file.

5. The index of the last element in a list x is always equal to len(x) False

6. The condition (a != b and a != c and b != c) evaluates to True True


only when the integer variables a, b, and c contain three different values.
The ‘finally’ clause is always executed after the code inside the ‘try’ block
7. True
is executed.

The following code raises a syntax error?


infile = open(‘abc.txt’)
8. data = infile.read() False

The following Python statements are valid and do not result in any errors:
9. date = ('May',7,24) True
print(date[0])

The result of the following comparison is True


10. 'alMawaleh' < 'Seeb District' False

Page 5 of 10
Question 3: [14 points] Functions
A. (10 points) Complete the following program that reads number of terms n and computes and prints the
series 𝐺(𝑛) defined as follows:
1 2 3 𝑛
𝐺(𝑛) = 1 + + + +⋯+
2! 3! 4! (𝑛 + 1)
You are requested to write the missing code indicated by the nine numbered bolded comments inside
the program code: (Refer to Figure 1 that shows a sample run of the program)

#Computes n factorial (n!), where 𝑛! = 1 ∗ 2 ∗ 3 ∗ 4 ∗ … ∗ (𝑛 − 1) ∗ 𝑛 (𝑒. 𝑔. 4! = 1 ∗ 2 ∗ 3 ∗ 4 = 24)


#(1)Write definition of function fact that receives number n and returns n factorial (3 Points)
to
def fact(n):________________________________________________
f = 1 ___________________________________________________
for I in range(2,n+1): ___________________________________
f = f * i______________________________________
return f
#Computes and prints G(n) series
def G(n):
total = 1
#(2)Complete code to print series starting text and stay on same line(See Figure1) (1 Point)

print('G(___%d__): 1 ' %_n, end= '' ________________)

#(3)Complete loop header to compute and print series terms (1 Point)

for __i in range (1,n+1)__________________:

#(4)Print current series term and stay on same line (See Figure1) (2 Point)

print('+ %d/%d! ' %(i,i+1),end='')_________________________

#(5)Add current series term to total (1 Points)

total += i / fact(i+1)_______
print(' = %.2f' %total)
def main():
#(6)Read number of terms n (See Figure1) (1 Point)

n= int(input('Enter number of terms n: '))_____________________________

#(7)Call function G(n) to print series G(n) (0.5 Point)

G(n)____________________________

#(8)Call function main to start the program (0.5 Point)

main()_____________

Figure1: Sample Run

Page 6 of 10
B. (4 points) A prime number is a positive integer greater than 1 that has exactly two divisors (1 and itself).
Complete the implementation of the following Python function to determine if a given number is a prime
number or not.

## define function isPrime


#@parameter: num can be positive or negative integer (no need to validate)
#@return True for num is prime, otherwise return False

def isPrime(num):
Sample output
if number <= 1:
return False 17 is a prime? True
for i in range(2, (number//0.5) + 1): 25 is a prime? False
if number % i == 0:
return False
return True

x = 17; y = 25
print(x, 'is a prime?', isPrime(x))
print(y, 'is a prime?', isPrime(y))

Alternate sol:
if num <= 1:
return False
for in range(2, num):
if num % i == 0:
return False
return True

Page 7 of 10
Question 4: [10 points] Lists and Strings initiate
A. (6 points) Complete the following Python program that creates a second list called list2 containing only
the 'light' numbers from list1. A number in list1 is considered 'light' if it is smaller than both of its
adjacent numbers. Make sure that list2 does NOT contain any repeated numbers.
2 95 6 7 8
list1= [6, I4, 5, 34, 7, 1, 6, 4, 3, 8]
91
# Create list2 containing only the "light" numbers from list1
list2=[]
#loop through list1
199
for i in range(1, len(list1) - 1):
#check if light number exists in list1
4314181614
if list1[i] < list1[i-1] and list1[i] < list1[i+1]:
#print the light number (see sample output)

print(list1[i]," is light element")


#check if light number not exists in list2
Sample output
if list1[i] not in list2: 4 is a light element
#add the light number to the end of list2 4 is a light element
1 is a light element
list2.append(list1[i]) 3 is a light element
# check if there are numbers in list2 list2: [4, 1, 3]

if len(list2)>0:
print("list2:", list2)
o
else:
print("no light elements in list 1")

B. (4 points) Complete the following program that reads an input string containing any type of characters.
The program should build a new string without vowels and numerical characters from the input string.
does
inputStr = input("Input a string : ") newsmins
#create an empty string in
newSt = ""

#loop through each character in the input string, adding it to the new
#string if it's neither numerical nor a vowel
for ch in inputStr: [1 point]
AEOUI
if not ch.lower() in "aeoui": [1 point]

if not ch.isdigit(): [1 point]

newst nest i
newSt+=ch [1 point] Sample run
#Display new string
print("New String is = ",newSt)
New String is =
i
Input a string : COMP2101 @Final Exam?

CMP @Fnl xm?

Page 8 of 10
Question 5: [6 points] Tables

Complete the following python program that display the content of the table as n x n matrix. Then finds and
prints the sum of diagonal elements (see Figure 2 showing diagonal elements).

matrix = [ [1, 2, 3, 4], [4, 5, 6, 3], [7, 8, 9, 6], [8, 6, 2, 4]]

#display the table as shown in the sample run


print("Matrix:")
for row in matrix:

for i in range(len(row)):

print(row[i], end=" ")

print()
diagonal_sum = 0 #initialize sum value
#find summation of the diagonal elements:
for i in range(len(matrix)):

diagonal_sum += matrix[i][i] Figure 2


# Display the total of diagonal elements
print("Sum of diagonal elements:", diagonal_sum)

Matrix:
1 2 3 4
4 5 6 3
7 8 9 6
8 6 2 4

Sum of diagonal elements: 19

sample run

Page 9 of 10
Question 6: [10 points] Files:
A. (6 points) What is the output of the following python code, given the input values in the ‘file.txt’ as shown
in Figure 3:

inFile= open('file.txt', 'r')


for line in inFile:
try:
info = line.split()
for i in range(len(info)):
info[i] = int(info[i])
result =sum(info)/len(info)
if result < 0:
raise RuntimeError(info)
print('Result:',result) Figure 3 ‘file.txt’
except ValueError :
print('Error#1:', info[i])
except RuntimeError as e:
print('Error#2:', str(e))
except Exception:
print('Error#3: Divide by Zero')
inFile.close()

Write output in the box:


Sample solution:
Result: 4.0 1.5pt
Error#3: Divide by Zero 1pt
Error#1: A 1pt
Result: 5.0 1.5pt
Error#2: [-1, -1] 1pt

B. (4 points) Using a while loop, Complete Python code to generate random integers in the range [0,100]
inclusive. Ensure that your code continues generating random numbers until it has stored five even
numbers in the output file called ‘out.txt’. Assume the random library is already imported as shown below.

from random import randint

Sample solution:

outf = open('out.txt', 'w') 0.75 pt


count = 0 0.25pt
while count<5: 0.5pt
r = randint(0,100) 0.75pt
if r % 2 == 0: #even 0.5pt
print(r, file=outf) 0.5pt
count +=1 0.25pt
outf.close() 0.5 pt

Page 10 of 10

You might also like