Uploaded by Utibe Udoudo

MODEL ANSWERS TO CPE311 EXAMS 2021-2022

advertisement
Session: 2021/2022
Semester: First
Date: April 13, 2023
CPE 311: Computer Programming & Languages III
Time allowed: 2 hours
Instruction: Attempt QUESTION 1 and ANY OTHER THREE (3) questions
MODEL ANSWERS
QUESTION 1
(a) Evaluate the following: (State reasons for your answers)
(i) math.ceil(5.132)
=> 6 (Next integer)
(ii) math.floor(3.943)
=>3 (previous integer)
(iii) math.factorial(6)
=>720 (6*5*4*3*2*1)
(iv) math.gcd(30,12)
=>6 (HCF of 30 and 12)
(v) math.pow(2,5)
=>32.0 (2 raised to the power of 5)
(b) What is the output of the formatted output statement below?
print("Addition: {0} \n Multiplication: {1}".format(3+4,3*4))
(5 marks)
(2 marks)
Addition: 7
Multiplication: 12
(c) Given that b = -5*2**3*5//2+8*5-3, what would b evaluate to in
python, following python’s rule of precedence of operators?
(3 marks)
Ans: -63
b = -5*8*5//2+8*5-3
b = -200//2+40-3
b = -100+40-3 = -63
(d) Mention any 10 built-in functions in Python.
(5 marks)
round(), divmod(), eval(), help(), len(), type(), list(), print(), pow(), sum(), zip(), etc
(e) Differentiate between definite and indefinite iteration.
(2 marks)
Definite iteration occurs when the number of times the loop should run is known at
program time. The For loop is mostly used for definite iteration. Indefinite iteration
occurs when the number of times the loop should repeat is not known at program time
but determined at run time. The While loop is used for indefinite iteration.
(f) Write a python program to print whole numbers from 10 to 1 in
descending order
(3 marks)
for i in range(10,0,-1):
print(i)
(g) What are the rules for naming variables (Identifiers) in Python?



Variables must begin with letters or underscores
Variables are case sensitive
No space is permitted in a variable name
(5 marks)



As a convention, use lower case letters for variable.
Variable names that consist of more than one word can be of toggleCase or joined
with underscore_characters
Python key words cannot be used as variable names
QUESTION 2
a. Given the string msg = “Python is an interesting programming language”, what
will be the output of the following operations?
(i) msg[13:24]
- interesting
(ii) msg[ :6]
- Python
(iii) msg[-20: ]
- programming language
(iv) msg.split() - ['Python', 'is', 'an', 'interesting', 'programming', 'language']
(v) msg.title() - Python Is An Interesting Programming Language
(vi) msg.find(“programming”) - 25
(vii) msg.replace(“programming”, “scripting”) - Python is an interesting
scripting language
(7 marks)
b. Discuss the four (4) “pillars” of Object Oriented Programming (OOP).
(8 marks)
Encapsulation is the mechanism of hiding of data implementation by restricting
access to public methods. Instance variables are kept private and accessor methods
are made public to achieve this.
Abstraction is an extension of encapsulation. It is the process of selecting data
from a larger pool to show only the relevant details to the object.
Inheritance is the ability of one object to acquire some/all properties of another
object. For example, a child inherits the traits of his/her parents. With inheritance,
reusability is a major advantage.
Polymorphism means one name many forms. It is further of two types — static and
dynamic. Static polymorphism is achieved using method overloading and dynamic
polymorphism using method overriding.
QUESTION 3
a. Write a python function called mode(), which takes a list of numbers as argument,
computes and returns the modal item (item with the highest frequency) in the list.
(8 marks)
def mode(data):
mode = data[0]
for d in data:
if data.count(d) > data.count(mode):
mode = d
return mode
b. Write a python function called median(), that takes a list of numbers as argument,
computes and returns the median of the distribution in the list.
(7 marks)
def median(num_list):
"""This function returns the median of a set of numbers in num_list"""
num_list.sort()
mid_point = len(num_list) // 2
if len(num_list) % 2 == 1:
mid = num_list[mid_point]
else:
mid = (num_list[mid_point - 1] + num_list[mid_point]) / 2
return mid
QUESTION 4
a. Given the list, Languages = [“C”, “Basic”, “Java”, “Python”, “Pascal”], write a
python instruction to accomplish the following tasks:
(i): Sort the list in ascending alphabetical order
(2 marks)
(ii) Sort the list in descending alphabetical order
(2 marks)
(iii) Add the item “Matlab” to the end of the list
(2 marks)
(iv) insert the item “PHP” between the second and the third item.
(2 marks)
(v) Delete (remove) the last item from the list
(2 marks)
(i) Languages.sort()
(ii) Languages.sort(reverse=True)
(iii) Languages.append("Matlab")
(iv) Languages.insert(2,'PHP')
(v) Languages.pop()
b. Write a recursive function to compute the Highest Common Factor (hcf) of any two
integers.
(5 marks)
QUESTION 5
a. Given the dictionary
dictA = {1: “One”, 2: “Two”, 3: “Three”, 4: “Four”, 5: “Five”},
write a python code to:
(i) generate the following output:
(3 marks)
1 => One
2 => Two
3 => Three
4 => Four
5 => Five
for k,v in dictA.items():
print(f"{k} => {v}")
(ii) print all the keys in the dictionary
(1 mark)
print(dictA.keys())
(iii) print all the values in the dictionary
print(dictA.values())
(iv) add the key-value pair, 6: “Six”, to the dictionary.
dictA[6] = “Six”
(v) print the value whose key is 3.
print(dictA[3]
(1 mark)
(2 marks)
(1 mark)
b. Write a python program that will take a sentence from a user, compute and display
the average length of words in the sentence.
(7 marks)
sentence = input("Enter a sentence: ")
words = sentence.split()
total_length = 0
for word in words:
total_length += len(word)
average_length = total_length / len(words)
print(average_length)
QUESTION 6
a. Write a python function, isPrime(n), which takes an integer, n, and determines if it
is a prime number.
(5 marks)
def isPrime(n):
flag = 0
if n==1:
flag = 1
#if n==2: True
else:
for i in range(2, n//2 + 1): #Check the first half of the number
for divisors
if (n%i == 0):
flag = 1
break
if flag == 0:
return True
else:
return False
b. Using the function created in Q6a above, create another function, firstPrimes(n),
which takes an integer, n, and prints out the first n prime numbers.
(5 marks)
def firstPrimes(n):
primes = []
count = 0
i = 2
while(count < n):
if(isPrime(i)):
primes.append(i)
count += 1
i += 1
return primes
c. A palindrome is a word that is same when spelled from the end as it is when spelled
from the beginning. Write a python function, isPalindrome(s), which takes a
string, s, and determines if it is a palindrome.
(5 marks)
def isPalindrome(s):
return (s == s[::-1])
Download