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.
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)
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'
def q1():
nw = randint(5,8)
c = randwords(1,nl=(1,1))[0]
ll = [randint(3,6) for i in range(nw)]
l = [randwords(1,nl=(ll[i],ll[i]))[0] for i in range(nw)]
n = random.choice(ll)
ol,on = copy.deepcopy(l), copy.deepcopy(n)
r = myfilter(l,n)
assert ( ol[ol.index(r)] == r and len(r) == on and
r not in ol[0:ol.index(r)] ),f"myfilter({ol},{on}) returns {r}"
Write a function, sumvalues(d)
where d
is a dictionary whose values are two-element tuples. The function should return a list containing the sum of each pair of values in each tuple.
For example, sumvalues({"ball":(1,2), "bat":(2,3), "Jane":(-1,5), "red":(1,9)})
should return [3, 5, 4, 10]
.
def sumvalues(d):
sum = 0
l = []
for k in d:
l += d[k][0]+ d[k][0]
return l
def sumvalues(d):
return [sum(v) for v in d.values()]
sumvalues({"ball":(1,2), "bat":(2,3), "Jane":(-1,5), "red":(1,9)})
[3, 5, 4, 10]
Write a function named dupval(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 the key appended to itself.
For example, dupval(['bcd', 'a', 'zebra'])
would return {'bcd': 'bcdbcd', 'a': 'aa', 'zebra': 'zebrazebra'}
.
import math
def dupval(l):
r = {}
for k in l:
r[k] = k+k
return r
def dupval(l):
return {k:k+k for k in l}
dupval(['bcd', 'a', 'zebra'])
{'bcd': 'bcdbcd', 'a': 'aa', 'zebra': 'zebrazebra'}
Define a string mypat
that is regular expression that matches a string that:
For example, your pattern should match the strings "N000" or 'NE12345' but not 'C12345' or 'NF12345' or 'N123456'.
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'N[AECLPRSX]\d{3,5}'
# 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)
ll = [randint(3,6) for i in range(nw)]
l = [randwords(1,nl=(ll[i],ll[i]))[0] for i in range(nw)]
n = random.choice(ll)
ol,on = copy.deepcopy(l), copy.deepcopy(n)
r = myfilter(l,n)
assert ( ol[ol.index(r)] == r and len(r) == on and
r not in ol[0:ol.index(r)] ),f"myfilter({ol},{on}) returns {r}"
def q2():
n = randint(4,6)
l1 = [randint(-2,10) for i in range(n)]
l2 = [randint(-2,10) for i in range(n)]
d = dict(zip(randwords(n),zip(l1,l2)))
ol1, ol2, od = copy.deepcopy(l1), copy.deepcopy(l2), copy.deepcopy(d)
r = sumvalues(d)
assert all([r[i] - ol1[i] == ol2[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 = dupval(l)
assert ( set(r.keys()) == set(ol) and
all([s[:len(ol[i])] == ol[i] for i,s in enumerate(r.values())]) and
all([s[len(ol[i]):] == ol[i] for i,s in enumerate(r.values())]) ), \
f"dupval({ol}) returns {r}"
def q4():
ok = [ (randwords(1,'N',(1,1))[0]+
(randwords(1,"AECLPRSX",(1,1))[0]+
randwords(1,string.digits,(3,5))[0]))
for i in range(randint(5,7)) ]
nok = "NT12345 NA654321 NA65".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.