COMP90059 Introduction to Programming Practice Examination, Summer Semester, 2020
Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit
Practice Examination, Summer Semester, 2020
COMP90059 Introduction to Programming
Question One [4 Marks]
Assuming the assignments i = 1, f = 2.0, s = "3" and t = "b4" have been made, evaluate the following code snippets:
(a) i + f
3.0
(b) str(i) + s
"13"
(c) int(f) + int(s)
5
(d) float(t[-1]) * i
4.0
Question Two [4 Marks]
Assuming the assignment s="internationalization" has been made, evaluate:
(a) s[1]
'n'
(b) s[:6] + s[11:13]
'internal'
(c) s[25]
IndexError: string index out of range
index error - this index does not exist, beyond the length of str
(d) s[-1:-10:-3]
nti, -1 starts, -10 stops, and getting every 3rd character
Question Three [4 Marks]
What is wrong with this code? How can you fix it?
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u:' OR
if letter in 'aeiou': more elegant way of checking for vowels
Question Four [4 Marks]
Given the assignment mylist = [3, ["green","eggs"], True, "computing"], evaluate the following statements and provide: (a) the value the expression evaluates
to; and (b) the value of mylist after the code statement has been executed. Assume that mylist is reassigned to its original value for each sub-question:
(a) mylist[2]
True
(a) True, (b) [3, ["green","eggs"], True, "computing"] – No change
(b) mylist[1][1][:-1]
(a) 'egg', (b) [3, ["green","eggs"], True, "computing"] – No change
egg slicing to position 1, and position 1 of list, and slicing until position -1
(c) mylist.pop()
(a) 'computing', (b) [3, ['green', 'eggs'], True] – last item of mylist is removed
computing if it's left blank it will remove last item
(d) mylist.append("new item")
a. None [3, ['green', 'eggs'], True, 'computing', 'new item']
(e) [str(x) for x in mylist] [1][:3]
(a) “[‘g”, (b) [3, ['green', 'eggs'], True, 'computing', 'new item'] – No change
Question 5 [4 Marks]
Rewrite the following code using a for loop, but preserving the remainder of the original code structure:
items = ['eggs', 'spam', 'moreeggs'] for count in range(0, len(items)):
print("We need to buy {0}!".format(items[count]))
items = ['eggs', 'spam', 'moreeggs'] for count in range(len(items)):
print("We need to buy {0}!".format(items[count]))
Question 6 [12 Marks]
Write a function freq_letter(string) that takes a single argument string (a string) and returns a
2-tuple containing the most common letter in string, and how many times it occurs. In case of a tie, it should return the letter that occurred first in the string. For example:
>>> freq_letter('aardvark') ('a', 3)
>>> freq_letter('wooloomooloo') ('o', 8)
>>> freq_letter('abacuses') ('a', 2)
"""
1. Get frequency of each letter - create dict
2. Get the letter with highest frequency
3. In case of a tie, max letter should be the letter that comes first """""
def freq_letter(string):
frequency_dict = {} #frequencies of letters
letter_positions = {} # for number 3, first occurrence of each letter
#1. Get the frequency of each letter
for i in range(len(string)):
letter = string[i]
if letter not in frequency_dict:
frequency_dict[letter] = 0 # {'h': 0, 'e': 0...}
letter_positions[letter] = i # {'h': 0, 'e': 1...}
frequency_dict[letter] += 1 print("FREQ DICT", frequency_dict) print("LETTER POSITIONS", letter_positions)
#2. Get the letter with the highest frequency
max_freq_count = 0 max_letter = ' '
fl_first_position = 0 #position of highest freq letter
for letter in frequency_dict:
if frequency_dict[letter] > max_freq_count: max_freq_count = frequency_dict[letter] max_letter = letter
fl_first_position = letter_positions[letter]
#3 In case of a tie, max letter should be the letter that comes first
elif frequency_dict[letter] == max_freq_count and letter_positions[letter] < fl_first_position: max_letter = letter
fl_first_position = letter_positions[letter]
return (max_letter, max_freq_count) print(freq_letter('hellooooo'))
Question 7 [12 Marks]
Write a function letter_overlap(s1, s2) that takes two string arguments (s1 and s2), and returns the number of unique letters that are present in both strings.
def letter_overlap(s1, s2):
print(set(s1)) print(set(s2))
return len(set(s1) & set(s2))
print(letter_overlap("heya", hey there"))
# Intersection &
# Union |
# Sets {1, 2, 3}
def letter_overlap(s1, s2):
print(set(s1)) print(set(s2))
return set(s1) | set(s2)
print(letter_overlap("heya", hey there"))
def letter_overlap(s1, s2):
print(set(s1)) print(set(s2))
return set(s1) - set(s2)
letter_overlap("heya", hey there")
Question 8 [4 Marks]
What is the output of the following code:
# max (numlist)
#10 - max number
#10 - max of list
-2 - min of list
NameError: avg is not defined
to calculate avg = we can use mean, need to import library for eg.
from statistics import mean extremum(lst, comp = mean))
Identify 3 errors in the following code, determine for each whether it is a syntax, run-time or logic error, and provide a replacement line which corrects the error.
use _ instead of hyphens
Logical error , instead of n we can use total
total = 0
greater_n = 0
total should be backspaced one indentation to be in line with if
syntax error, no indentation
Question 10 [6 Marks]
Write a code snippet to produce each of the following exceptions and associated error messages:
· SyntaxError: invalid syntax
· ZeroDivisionError: division by zero
· KeyError: 1
· IndexError: list index out of range
· TypeError: can only concatenate str (not "int") to str
· ValueError: invalid literal for int() with base 10: ’a’
"]
2022-10-11