ELEX 4653 Sample Exam 1 Solutions

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 "Solution to question N may be correct." at the bottom of the notebook means that your answer to question N may be correct.

  • When the exam time is over, save the notebook (the .ipynb file) and upload it to the appropriate dropbox on the course web site.

Question 1

This question tests your ability to iterate through a data structure while testing, creating and/or modifying objects.

Write a function named addkey that takes one argument named x. The argument is a dictionary where the keys are integers and the values are strings. Modify the dictionary x so that the key is appended to the value. For example, if x is { 3: 'x', 7: 'Page ', 4: '' } the result should be { 3: 'x3', 7: 'Page 7', 4: '4' }. Your function should return the modified dictionary.

In [1]:
def addkey(x):
    for k in x:
        x[k]=x[k]+str(k)
    return x

Question 2

This question tests your ability to work with compound (nested) data structures.

Write a function named elemadd that takes one list argument named x. x is a list whose elements are n-element lists. Your function should return a list containing the sum of the corresponding elements of the lists in x. For example if x is [[1,2], [3,-1], [7,8]] then elemadd(x) should return [11,9]. Your solution may only use the functions len, range and enumerate.

In [2]:
def elemadd(x):
    m=len(x[0])
    s=[0]*m
    for t in x:
        for i in range(m):
            s[i] += t[i]
    return s

Question 3

This question tests your ability to write a recursive function.

Write a recursive function named oddcall that takes a list argument named l and a function argument named f. f takes one argument. Your function should call the function f with each value in the argument list x that is odd (it's the value that should be odd, not the index). For example oddcall([1,2,3,4],print) would print lines with 1 and 3.

In [3]:
def oddcall(l,f):
    if not l:
        return
    else:
        if l[0] % 2:
            f(l[0])
        oddcall(l[1:],f)

Question 4

This question tests your ability to write a regular expression.

Set the variable pat to a regular expression that matches part numbers created according to the following sequence:

  1. begins with the letters AT
  2. followed by an optional letter F
  3. followed by a two- or three-digit number
  4. followed by zero or more of the letters B, Q or Z, in any order
  5. a dash (-)
  6. a one- or two-digit number
In [4]:
pat=r'^ATF?\d\d\d?[BQZ]*-\d\d?'
In [5]:
# exam validation code; do not modify
def examcheck():
    
    def checksorted(l):
        assert all((l[i] <= l[i+1] for i in range(len(l)-1))), \
            "result is not sorted: {}".format(l)

    def checkfunctions(f,l):
        u=[s for s in f.__code__.co_names if s not in l]
        assert not u, "You used the function(s): {}".format(u)
        
    def checkrecursive(f):
        s=f.__name__
        assert s in f.__code__.co_names, "{} is not recursive".format(s)

    def checkhash(l,n):
        import hashlib
        # print(hashlib.md5(''.join(l).encode('utf8')).hexdigest())
        assert hashlib.md5(''.join(l).encode('utf8')).hexdigest() == n, \
                'wrong values in list: {} ... {}'.format(l[0],l[-1])
    
    def checkre(pat,ok,nok):
        import re
        for s in ok:
            assert re.search(pat,s), \
                "pattern '{}' didn't match string '{}'".format(pat,s)
        for s in nok:
            assert not re.search(pat,s), \
                "pattern '{}' matched string '{}'".format(pat,s)

    def q1():   
        from random import randint, shuffle
        import copy
        n=list(range(randint(3,6)))
        shuffle(n)
        x={k:chr(randint(97,122))*randint(1,3) for k in n}
        x0=copy.deepcopy(x)
        y=addkey(x)
        assert len(y) == len(x)
        assert all(int(y[k][-1]) == k for k in y)
        assert all(y[k][:-1] == x0[k] for k in y)

    def q2():
        from random import randint
        checkfunctions(elemadd,['len', 'range', 'enumerate'])
        m=randint(2,4)
        x=[list(randint(0,9) for i in range(m)) for j in range((randint(2,4)))]
        s=[sum(t) for t in zip(*x)]
        y=elemadd(x)
        assert len(y) == m
        assert y == s   

    def q3():
        from random import randint
        checkrecursive(oddcall)
        l=[randint(0,9) for i in range(randint(4,9))]
        fl=[]
        found=lambda x:fl.append(x)
        oddcall(l,found)
        cl=list(filter(lambda x:x%2,l))
        assert fl == cl, "oddcall({}) calls f with: {}, not {}".format(l,fl,cl)  

    def q4():
        ok=['AT00-0', 'ATF999BQZ-99', 'ATF999BQZ-12', 'ATF999BQZ-99', 'ATF999BQZ-34' ]
        nok=[' AT00-0', 'ATFF999BQZ-123', 'ATF9BQZ-99', 'ATF999BQZ33', 'ATF9999ZB-99' ]
        checkre(pat,ok,nok)

    for i,s in ((i,'q%d'%i) for i in range(1,20)):
        if s in locals():
            try:
                locals()[s]()
                print("Solution to question {} may be correct.".format(i))
            except Exception as e:
                print("Failed check for question {}: {}".format(i,e))    

examcheck()
Solution to question 1 may be correct.
Solution to question 2 may be correct.
Solution to question 3 may be correct.
Solution to question 4 may be correct.