Answer all four (4) questions.
You have 110 minutes to complete the exam.
This is an open-book exam. All written material is allowed.
No electronic devices other than a flash drive and the lab PC may be used during the exam.
No communication with others (electronic, verbal, written or otherwise) is allowed during the exam. Violations will result in a mark of zero and disciplinary action.
Add the Python code described below in the cells provided.
Test your code using the menu item Cell ► Run All
The message Question n OK. at the bottom of the notebook means that no errors were found in your answer to question n.
When your are done or when the exam time is over, save the notebook (the .ipynb file) and upload it to the appropriate Assignment folder on the course web site.
Write a function named myfilter(l,c)
where l
is a list of strings and c
is a character. The function should return the first item in l
whose first letter is c
.
For example, myfilter(['a', 'xyzzy', 'abc', 'de'],'x')
would return xyzzy'
.
def myfilter(l,c):
for i in range(len(l)):
if l[i][0] == c:
return l[i]
def myfilter(l,c):
return [s for s in l if s[0]==c][0]
myfilter(['a', 'xyzzy', 'abc', 'de'],'x')
'xyzzy'
Write a function, minvalues(d)
where d
is a dictionary whose values are tuples of integers. The function should return a list containing the smallest integer in each tuple. Hint: there is a built-in function named min()
.
For example, minvalues({"ball":(3,1,2), "bat":(2,3), "Jane":(-1,5), "red":(10,9)})
should return [1,2,-1,9]
.
def minvalues(d):
sum = 0
l = []
for k in d:
l += min(d[k])
return l
def minvalues(d):
return [min(v) for v in d.values()]
minvalues({"ball":(3,1,2), "bat":(2,3), "Jane":(-1,5), "red":(10,9)})
[1, 2, -1, 9]
Write a function named numvals(l)
where l
is a list of strings. The function should return a dictionary whose keys are the values in l
and whose values are a string consisting of the index of string in l
followed by the key. Hint: the str()
function converts an integer to a string.
For example, numvals(l)(['bcd', 'a', 'zebra'])
would return {'bcd': '0bcd', 'a': '1a', 'zebra': '2zebra'}
.
def numvals(l):
r = {}
for i in range(len(l)):
r[l[i]] = str(i)+l[i]
return r
def numvals(l):
return {k:f"{i}{k}" for i,k in enumerate(l)}
numvals(['bcd', 'a', 'zebra'])
{'bcd': '0bcd', 'a': '1a', 'zebra': '2zebra'}
Define a string mypat
that is regular expression that matches a string that:
For example, your pattern should match the strings "CF104" or 'CC130H' but not 'F104' or 'CX123' or 'CF1234' or 'CF100b'.
Your answer in the cell below should be an assignment to the variable mypat
. For example, your answer might look like:
mypat = r'A{3}x+--' # not the corect answer
mypat = r'C[CEFHPTU]\d{3,3}[A-Z]?'
# lab validation code; do not modify
def labcheck():
import copy, random, re, string, types
from random import randint
def checkre(pat,ok,nok):
for s in ok:
assert re.fullmatch(pat,s), \
f"pattern '{pat}'\n did not match string '{s}'"
for s in nok:
assert not re.fullmatch(pat,s), \
f"pattern '{pat}'\n matched string '{s}'"
def randwords(n,chars=string.ascii_lowercase,nl=(2,5)):
l = set()
while len(l)<n:
l |= set((''.join([chars[randint(0,len(chars)-1)] for i in range(randint(*nl))]),))
return list(l)
def q1():
nw = randint(5,8)
c = randwords(1,nl=(1,1))[0]
l = [s for s in [randwords(1)[0] for i in range(100)] if s[0] != c]
l = l[0:nw]
i = randint(0,nw-1)
l[i] = c+l[i]
ol,oc = copy.deepcopy(l), copy.deepcopy(c)
r = myfilter(l,c)
assert ( r == ol[i]),f"myfilter({ol},'{oc}') returns {r}"
def q2():
n = randint(4,6)
v = [tuple([randint(-2,10) for i in range(randint(1,4))]) for i in range(n)]
k = randwords(n)
d = dict(zip(k,v))
od = copy.deepcopy(d)
r = minvalues(d)
assert all([all([v[i][j] >= r[i] for j in range(len(v[i]))]) for i in range(n)]), \
f"sumvalues({od}) returns {r}"
def q3():
n = randint(3,5)
l = randwords(n)
ol = copy.deepcopy(l)
r = numvals(l)
assert (set(r) == set(ol) and all([v[1:] == ol[int(v[0])] for v in r.values()]) ), \
f"numvals({ol}) returns {r}"
def q4():
ok = [ (randwords(1,'C',(1,1))[0]+
(randwords(1,"CEFHPTU",(1,1))[0]+
randwords(1,string.digits,(3,3))[0])+
(randwords(1,string.ascii_uppercase,(1,1))[0] if randint(0,1) else ''))
for i in range(randint(5,7)) ]
nok = "'H104 CX123 CF1234 CF20 CF999b CFF100".split()
checkre(mypat,ok,nok)
for s,i in [(s,s[1:]) for s in locals().keys() if re.search(r'q\d+',s)]:
try:
locals()[s]()
print(f"Question {i} OK.")
except Exception as e:
print(f"Failed check for Question {i}: {e}")
labcheck()
Question 1 OK. Question 2 OK. Question 3 OK. Question 4 OK.