ELEX 4653 Final Exam 4

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

The code below generates a list of strings (s1) and a list of boolean (True or False) values (t1). Write code to create a list y1 that has the same number of values as s1 and where each value is the corresponding string in s1 converted to upper case if the corresponding element of t1 is True and unchanged otherwise. For example, if s1 is [ "dog", "cat", "turtle" ] and t1 is [ True, True, False ] then y1 should contain "DOG","CAT","turtle". Hint: you can use str.upper().

In [6]:
from random import randrange as rr
s1=[''.join([chr(rr(97,123)) for j in range(rr(2,6))]) for i in range(rr(3,7))]
t1=[bool(rr(0,2)) for i in range(len(s1))]

y1=[s.upper() if u else s for s,u in zip(s1,t1)]
s1,t1,y1
Out[6]:
(['zh', 'ovbgf', 'qr', 'jyuyh'],
 [False, False, False, True],
 ['zh', 'ovbgf', 'qr', 'JYUYH'])

Question 2

The code below sets the variable s2 to a list of strings and the variable i2 to a list of integers. Write code that creates a dictionary d2 where each entry's key/value pair is a key taken from s2 and a value taken from the corresponding element of i2. For example, if x2 is ['a', 'b', 'cc'] and y2 is [2, 3, 5] then d2 should be {'a':2, 'b':3, 'cc':5}.

In [7]:
from random import randrange as rr
s2=[''.join([chr(rr(97,123)) for j in range(rr(3,6))]) for i in range(rr(3,7))]
i2=[rr(1,20) for i in range(len(s2))]

d2={k:v for k,v in zip(s2,i2)}
s2,i2,d2
Out[7]:
(['psi', 'ltryk', 'rxb', 'ldy'],
 [11, 8, 4, 12],
 {'ldy': 12, 'ltryk': 8, 'psi': 11, 'rxb': 4})

Question 3

Write a function called ispal(s) that takes a string argument s and returns True if s is a palindrome (a word that reads the same forwards or backwards). For example it would return True for 'anna' or 'bob' and False for 'ann' or 'rob'. Hint: for a palindrome the *i*'th element is equal to the -*i*'th element for all *i* or, equivalently, the reversed string is equal to the string*.

In [8]:
def ispal(s):
    return s == s[::-1]

Question 4

The code below creates the numpy array x. Create a 5x2 (5 rows, 2 columns) matrix called a by reshape()ing x. Create a 2x5 matrix called b by transposing y. Set c to the matrix product of a times b.

In [9]:
import numpy as np
x=np.random.random(10)

a=x.reshape(5,2)
b=a.T
c=a.dot(b)
x,a,b,c
Out[9]:
(array([ 0.16004604,  0.4831394 ,  0.62969489,  0.79173596,  0.44616274,
         0.79708479,  0.57652204,  0.38960684,  0.73016126,  0.04363195]),
 array([[ 0.16004604,  0.4831394 ],
        [ 0.62969489,  0.79173596],
        [ 0.44616274,  0.79708479],
        [ 0.57652204,  0.38960684],
        [ 0.73016126,  0.04363195]]),
 array([[ 0.16004604,  0.62969489,  0.44616274,  0.57652204,  0.73016126],
        [ 0.4831394 ,  0.79173596,  0.79708479,  0.38960684,  0.04363195]]),
 array([[ 0.25903841,  0.48329901,  0.45650965,  0.28050449,  0.13793974],
        [ 0.48329901,  1.02336149,  0.91202709,  0.67149873,  0.49432379],
        [ 0.45650965,  0.91202709,  0.83440535,  0.56777234,  0.36054911],
        [ 0.28050449,  0.67149873,  0.56777234,  0.48417116,  0.43795337],
        [ 0.13793974,  0.49432379,  0.36054911,  0.43795337,  0.53503921]]))
In [10]:
# exam validation code; do not modify
def examcheck():
    from random import randrange as rr
    import numpy as np
    
    try:
        if all(s.isupper() == t for s,t in zip(y1,t1)):
            print("Solution to question 1 may be correct.") 
    except Exception as e:
        print(e)
        
    try:
        if all(d2[k] == i2[v] for k,v in {s:i for i,s in enumerate(s2)}.items()):
            print("Solution to question 2 may be correct.")
    except Exception as e:
        print(e)
        
    try:
        s3=[''.join([chr(rr(97,123)) for j in range(rr(2,5))]) for i in range(rr(4,8))]
        t3=[rr(0,2) for _ in range(len(s3))]
        s3=[s+s[::-1] if t else s+s for s,t in zip(s3,t3)]
        if all(ispal(s) == t for s,t in zip(s3,t3)):
            print("Solution to question 3 may be correct.")
    except Exception as e:
        print(e)
        
    try:
        if (a.shape, b.shape, np.array_equal(c.T,c)) == ((5,2), (2,5), True):
            print("Solution to question 4 may be correct.")
    except Exception as e:
        print(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.