ELEX 4653 Final Exam 1, May 2022¶

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 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 stringrep(l1) that takes a list of strings and returns a list containing strings made up by repeating each element of the string a number of times equal to the index of the string in the list.For example, if l = [ 'AB', 'CDE', 'xyz', 'z'] then stringrep(l) would return ['', 'CDE', 'xyzxyz', 'zzz']. Hint: multiplication (*) can be used to repeat a string.

In [ ]:
 

Question 2¶

Write a function valfilter(l) that takes a list of two-element tuples and returns a list of those tuples where the first element of each tuple is less than the value of the second element. For example, if l = [(1,2), (4,3), (5,6)] then valfilter(l) would return [(1, 2), (5, 6)].

In [ ]:
 

Question 3¶

Write a function named shout(l) that takes a list of strings l and returns a list containing each string l converted to upper case. For example, if l = ['abc', 'def', "xyz"] then shout(l) would return ['ABC', 'DEF', "XTZ"].

In [ ]:
 

Question 4¶

Write a string named license that is a regular expression that matches strings that consist of:

  • an optional digit
  • three upper-case letters
  • three digits

This regular expression will match, for example any of: '1ABC123', 'XYZ789', but not any of: '11ABC123', 'ABc123', 'ABC123', 'AB123', 'ABCD123', 'ABC12', 'ABC1234', 'ABC'.

In [ ]:
 
In [1]:
# exam validation code; do not modify
def examcheck():
    import copy, random, re, string, types
    from random import randint
    from random import randint, choices, shuffle, random
    
    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_letters,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(): # stringrep(l)
        n=randint(3,5)
        l = randwords(n,string.ascii_uppercase,(1,4))
        ol = copy.deepcopy((l))
        r = stringrep(l)
        assert len(r) == len(ol) and \
            all([len(s) == n*len(ol[n]) for n,s in enumerate(r)]) and \
            all([all([n==0 or s[i] == s[i%len(ol[n])] for i,c in enumerate(s)]) for n,s in enumerate(r)]), \
            f"stringrep({ol}) returns {r}"

        
    def q2(): #valfilter
        n = randint(4,5)
        l = [(randint(0,10), randint(0,10)) for i in range(n)]
        ol = copy.deepcopy(l)
        r=valfilter(l)
        notused = set(ol) - set(r)
        assert notused.union(set(r)) == set(ol) and \
            all([a<b for a,b in r]) and all([a>=b for a,b in notused]), \
            f"valfilter({ol}) returns {r}"

        
    def q3(): #shout
        n=randint(4,6)
        l = randwords(n,string.ascii_letters,(1,4))
        ol=copy.deepcopy(l)
        r = shout(l)
        assert len(r) == len(ol) and all([s.lower() == ol[i].lower() for i,s in enumerate(r)]) and \
            all([s.isupper() for s in r]), \
            f"shout({ol}) returns {r}"

        
    def q4(): #license
        ok = [(randwords(1,string.digits,(1,1))[0] if randint(0,1) else '')+
                randwords(1,string.ascii_uppercase,(3,3))[0]+
                randwords(1,string.digits,(3,3))[0] for i in range(randint(5,7))]
        nok = "11ABC123 ABc123 AB123 AX123 ABCD123 ABC12 ABC1234 ABC".split()
        checkre(license,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}")    

examcheck()
Failed check for question 1: name 'stringrep' is not defined
Failed check for question 2: name 'valfilter' is not defined
Failed check for question 3: name 'shout' is not defined
Failed check for question 4: first argument must be string or compiled pattern