ELEX 4653 Exam 2¶

Instructions:¶

  • 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.

Question 1¶

Write a function named myfilter(l,a,b) where l is a list of integers and a and b are integers. The function should return the first item in l which is between a and b (inclusive).

For example, myfilter([5,1,2,3],2,4) would return 2 and myfilter([5,1,2,3],0,4) would return 1

In [1]:
def myfilter(l,a,b):
    for i in range(len(l)):
        if l[i] >= a and l[i] <= b:
            return l[i]

def myfilter(l,a,b):
    return [i for i in l if a<=i<=b][0]

myfilter([5,1,2,3],2,4), myfilter([5,1,2,3],0,4)
Out[1]:
(2, 1)

Question 2¶

Write a function, sumvalues(d) where d is a dictionary. The function should return the sum of all the values in the dictionary.

For example, sumvalues({"ball":1, "bat":2, "Jane":-1, "red":9}) should return 11.

In [2]:
def sumvalues(d):
    sum = 0
    for k in d:
        sum += d[k] 
    return sum

def sumvalues(d):
    return sum(d.values())

sumvalues({"ball":1, "bat":2, "Jane":-1, "red":9})
Out[2]:
11

Question 3¶

Write a function named sroot(l) where l is a list of floats. The function should return a dictionary whose keys are the values in l and whose values are the square roots of the corresponding key. Hint: the sqrt function is found in the math module.

For example, sroot([4.0, 36, 9.0]) would return {4.0: 2.0, 36: 6.0, 9.0: 3.0}.

In [3]:
import math

def sroot(l):
    r = {}
    for k in l:
        r[k] = math.sqrt(k)
    return r

def sroot(l):
    return {k:math.sqrt(k) for k in l}

sroot([4.0, 36, 9.0])
Out[3]:
{4.0: 2.0, 36: 6.0, 9.0: 3.0}

Question 4¶

Define a string mypat that is regular expression that matches a string that:

  • starts with a number that has 1 to 4 digits
  • followed by either a dash ('-') or a colon (':')
  • followed by four upper-case letters

For example, your pattern should match the strings "0:AAAA" or '9999-ZZZZ' but not '12345:AAAA' or '1234.AAAA' or '1234:ABC'.

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
In [4]:
mypat = r'\d{1,4}[-:][A-Z]{4}'
In [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():
        c = randint(20,30)
        a = [randint(0,c-5) for i in range(5)]
        b = [randint(c+5,99) for i in range(5)]
        l = a+[c]+b
        random.shuffle(l)
        ol = copy.deepcopy(l)
        r = myfilter(l,c-5,c+5)
        assert r == c,f"myfilter({ol},{c-5},{c+5}) returns {r}"
        
    def q2():
        s = randint(5,9)
        n = s
        l = []
        while n > 0:
            l += [randint(-1,5)]
            n -= l[-1]
        l += [n]
        k = randwords(len(l))
        d = dict(zip(k,l))
        od = copy.deepcopy(d)
        r = sumvalues(d)
        assert r == sum(l),f"sumvalues({od}) returns {r}"
    
    def q3():
        l = list(set([randint(0,10) for i in range(8)]))
        random.shuffle(l)
        ls = [x*x for x in l]
        ols = copy.deepcopy(ls)
        r = sroot(ls)
        assert set(r) == set(ols) and all([v*v == k for k,v in r.items()]), \
            f"sroot({ols}) returns {r}"

    def q4():
        ok = [ (randwords(1,string.digits,(1,4))[0]+
               (randwords(1,":-",(1,1))[0]+
                randwords(1,string.ascii_uppercase,(4,4))[0]))
                  for i in range(randint(5,7)) ]
        nok = "11111:AAAA 0=AAAA 0:AAA".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.