ELEX 4653 Lab 2¶

This lab provides practice on expressions, lists, dictionaries, control flow statements and functions.

April 28, 2022.

Instructions:

  • Modify this notebook by adding the Python code described below.

  • Test your code using the menu item Cell ► Run All

  • Save the notebook (the .ipynb file) and upload it to the appropriate Assignment folder on the course web site.

Question 1¶

Write a function divisibles(a,b,m) that takes three integer arguments and returns values between a and b (inclusive) that are multiples of m. For example, divisibles(4,15,5) would return [5, 10, 15] and divisibles(3,31,10) would return [10, 20, 30].

In [1]:
def divisibles(a,b,m):
    return [i for i in range(a,b+1) if not i%m]

divisibles(4,15,5), divisibles(3,31,10)
Out[1]:
([5, 10, 15], [10, 20, 30])

Question 2¶

Write a function whopassed(l) whose argument is a list of three-element tuples. The first element of each tuple is a string with a student ID, the second element of the tuple is the course theory mark and the third is the lab mark. The function should return a list of the tuples for which both the theory and lab marks were 0.5 or more.

For example, if l is [ ("A00", 0.75, 0.5), ("A01", 0.45, 0.65), ("A02", 0.80, 0.55), ("A03", 0.65, 0.25), ("A04", 0.45, 0.495) ] then whopassed(l) should return [('A00', 0.75, 0.5), ('A02', 0.8, 0.55)].

In [2]:
l=[("A00", 0.75, 0.5), ("A01", 0.45, 0.65), ("A02", 0.80, 0.55), 
   ("A03", 0.65, 0.25), ("A04", 0.45, 0.495) ]

def whopassed(l):
    p=[]
    for t in l:
        if t[1] >= 0.5 and t[2] >= 0.5:
            p.append(t)
    return p

whopassed(l)
Out[2]:
[('A00', 0.75, 0.5), ('A02', 0.8, 0.55)]

Question 3¶

Write a function busydays(l) that takes a list of integers with values between 0 and 6 representing the days of the week and returns a list of 7 values that are True if that day appears in l or False if it does not. For example busydays([0,0,5,3]) would return [True, False, False, True, False, True, False] and busydays([5, 6, 6, 5, 3, 0]) would return [True, False, False, True, False, True, True].

In [3]:
l=[5, 6, 6, 5, 3, 0]

def busydays(l):
    used = 7*[False]
    for i in l:
        used[i] = True
    return used

busydays(l)
Out[3]:
[True, False, False, True, False, True, True]

Question 4¶

Write a function select(sel, a, b) that takes three equal-length lists and returns a list. For each element of sel that is True, the returned list has the corresponding value from a, otherwise it has the corresponding value from b. For example, if sel=[False, False, True, False] and a=[92, 76, 22, 60] and b=[6, 29, 77, 40] then select(sel,a,b) returns [6, 29, 22, 40].

In [4]:
def select(sel,a,b):
    return[(b,a)[int(s)] for s,a,b in zip(sel,a,b)]

sel=[False, False, True, False]
a=[92, 76, 22, 60]
b=[6, 29, 77, 40]

select(sel,a,b)
Out[4]:
[6, 29, 22, 40]

Question 5¶

Write a function mark(l) that takes an argument that is a list of numbers. Your function should return the average of the smallest and largest values.

For example, if l = [1,2,3,4,1] mark(l) should return 2.5.

Hint: The sorted(), max() and min() functions.

In [5]:
l = [1,2,3,4,1]

def mark(l):
    return (max(l)+min(l))/2

mark(l)
Out[5]:
2.5

Question 6¶

Write a function translate(l,d) that takes a list of strings and a dictionary returns a list of strings translated according the keys and values in the dictionary.

For example, if l=[ 'one', 'two', 'two', 'four'] and d={ 'one':'uno', 'two': 'zwei', 'three': 'troi', 'four': 'τέσσερα' } then names(l,d) would return ['uno', 'zwei', 'zwei', 'τέσσερα'].

In [6]:
l=[ 'one', 'two', 'two', 'four']
d={ 'one':'uno', 'two': 'zwei', 'three': 'troi', 'four': 'τέσσερα' }

def translate(l,d):
    return [d[k] for k in l]
translate(l,d)
Out[6]:
['uno', 'zwei', 'zwei', 'τέσσερα']
In [7]:
# lab validation code; do not modify
def labcheck():
    import random, copy, string, re
    from random import randint
    
    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():
        while True:
            a=random.randint(1,10)
            b=a+random.randint(20,80)
            m=random.randint(3,9)
            l=divisibles(a,b,m)
            if (b-a)//m < 10 and (b-1)//m > 3:
                break
        assert all([((i in l and (i//m*m == i)) or 
               ((i not in l) and (i//m*m != i))) for i in range(a,b+1)]), \
               f"divisibles({a},{b},{m}) returns {l}"

    def q2():
        n = random.randrange(5,9)
        m = random.randrange(5,9)
        l=[(f"A{m+i:02g}", 0.2+0.8*random.random(), 0.2+0.8*random.random())  
           for i in range(n)]
        p=whopassed(copy.deepcopy(l))
        assert all([ (t in p and int(t[1]+0.5) and int(t[2]+0.5)) or 
                     (t not in p and not int(t[1]+0.5) or not int(t[2]+0.5)) 
                     for t in l]), \
                       f"whopassed({l}) returns {p}"
 
    def q3():
        n=random.randint(5,10)
        l=[random.randint(0,6) for i in range(n)]
        b=busydays(copy.deepcopy(l))
        assert len(b) == 7 and \
            all([t and i in l or not t and i not in l for i,t in enumerate(b)]), \
            f"busydays({l}) returns {b}"
        
    def q4():
        n=random.randrange(4,7)
        a,b = [[random.randrange(0,100) for j in range(n)] for i in (1,2)]
        sel = [bool(random.randrange(0,2)) for j in range(n)]

        l=select(copy.deepcopy(sel),copy.deepcopy(a),copy.deepcopy(b))

        assert  len(l) == len(sel) and \
            not any([s*a+(not s)*b - l[i] for i,s,a,b in zip(range(len(sel)),sel,a,b)]), \
            f"select({sel},{a},{b}) returns {l}"
        
    def q5():
        n=random.randrange(3,5)
        l=[random.randrange(0,10) for i in range(n)]
        m=mark(copy.deepcopy(l))
        assert m*2 - sorted(l)[0] == max(l), \
            f"mark({l}) returns {m}"
        
    def q6():
        m=random.randrange(3,5)
        k=randwords(m)
        v=randwords(m)
        d=dict(zip(k,v))
        id=dict((v, k) for k, v in d.items())
        n=random.randrange(3,5)
        l=[k[random.randrange(0,m-1)] for i in range(n)]
        t=translate(copy.deepcopy(l),copy.deepcopy(d))
        assert len(t) == len(l) and all([id[s] == l[i]  for i,s in enumerate(t)]), \
                    f"translate({l},{d}) returns {t}"
   
    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.
Question 5 OK.
Question 6 OK.