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 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,f)
where l
is a list of integers and f
is a list of integers. The function should return the first item in l
which is included in f
.
For example, myfilter([5,1,2,3],[3,4])
would return 3
.
def myfilter(l,f):
return [i for i in l if i in f][0]
def myfilter(l,f):
for i in range(len(l)):
if l[i] in f:
return l[i]
myfilter([5,1,2,3],[3,4])
3
Write a function, onlyproper(s)
where s
is a set of strings. The function should return a set of all the items in s
that begin with a capital letter.
For example, onlyproper({"ball", "bat", "Jane", "red", "John")})
should return {"Jane", "John"}
(possibly in a different order).
def onlyproper(s):
return {w for w in s if w[0] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' }
def onlyproper(s):
r = set()
for w in s:
if w[0] >= 'A' and w[0] <= 'Z':
r.add(w)
return r
onlyproper({"ball", "bat", "Jane", "red", "John"})
{'Jane', 'John'}
Write a function named strlen(l)
where l
is a list of strings. The function should return a dictionary whose keys are the strings in l
and whose values are the length of the corresponding key.
For example, strlen(['zebra', 'bat', 'Orangutan'])
would return {'zebra':5, 'bat':3, 'Orangutan':9}
.
def strlen(l):
return {k:len(k) for k in l}
def strlen(l):
r = {}
for s in l:
r[s] = len(s)
return r
strlen(['zebra', 'bat', 'Orangutan'])
{'zebra': 5, 'bat': 3, 'Orangutan': 9}
Define a string mypat
that is regular expression that matches a string:
For example:
mypat = r'A{3}x+--'
(the above is not the correct answer).
mypat = r'[ABC]\d{3,4}[-:](([a-z][a-z])|(\d\d))'
# 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():
l = list(set([randint(0,99) for i in range(100)]))
f = l[0:5]
l = l[5:9]+[f[0]]
ok = f[0]
random.shuffle(l)
ol = copy.deepcopy(l)
of = copy.deepcopy(f)
r = myfilter(l,f)
assert r == ok,f"myfilter({ol},{of}) returns {r}"
def q2():
sl = randwords(5)
su = [s.capitalize() for s in randwords(5)]
s = sl+su
random.shuffle(s)
s = set(s)
os = copy.deepcopy(s)
r = onlyproper(s)
assert set(r) == set(su),f"onlyproper({os}) returns {r}"
def q3():
l = randwords(8)
ol = copy.deepcopy(l)
r = strlen(l)
assert all([len(k) == v for k,v in r.items()]) and set(r.keys()) == set(ol), \
f"strlen({ol}) returns {r}"
def q4():
ok = [ (randwords(1,"ABC",(1,1))[0])+
randwords(1,string.digits,(3,4))[0]+
randwords(1,"-:",(1,1))[0]+
(randwords(1,string.digits,(2,2))[0] if randint(0,1) else
randwords(1,string.ascii_lowercase,(2,2))[0])
for i in range(randint(5,7))]
nok = "D123-xx A12345-xx A123.xx A123-XX A123-x1".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.