Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

Midterm Exam

ICS 33 Summer 2022

Question 1: 10 points (2 points each)

Multiple choice: circle the choice(s). There may be more than one correct choices.          (1) Which data types are immutable?                                                                                      a.   List                                                                                                                                        b.  Tuple                                                                                                                                     c.   String                                                                                                                                    d.   Dictionary                                                                                                                             e.   Set                                                                                                                                        (2) Which elements have to be unique?                                                                                  a.   List elements                                                                                                                       b.  Tuple elements                                                                                                                    c.   Dictionary keys                                                                                                                    d.   Dictionary values                                                                                                                 e.   Set elements                                                                                                                        (3) Which of the following statement(s) can access the last element of a list named lst? a . lst[:1]                                                                                                                      b . lst[1:]                                                                                                                      c . lst[len(lst)- 1]                                                                                                     d . lst[len(lst)]                                                                                                         e . lst[- 1]                                                                                                                      (4) Which of the following statement(s) can be executed?                                                    a . s  =  {1,2,3};  s[0]                                                                                                 b . d  =  {‘a’:  1,  ‘b’:  2};  d[0]                                                                              c . l  =  [1,2,3];  l[0]                                                                                                 d . a  =  ‘test’;  a[0]                                                                                                   e . n  =  10;  n[0]                                                                                                           (5) Which of the following can you use the sort() function on?                                         a .  [0,  - 1,  10]                                                                                                             b .  {‘a’:  1,  ‘b’:  - 1}                                                                                                 c .  {1,  - 1,  20}                                                                                                             d. 7301

Question 2: 10 points (2 points each)

Code tracing: Write the expected output. If you think the code will result in an error, you can write Error without specifying the error type.

(1) What is the output of the following code snippet?

d  =  {‘a’:1,   ‘b’:2,   ‘c’:3}

for  key  in  d:

val  =  d[key]

val  =  val   **2

print(d)

(2) What is the output of the following code snippet?

def  foo(L):

M  =  sorted(L)

N  =  L[:]

M .append(L .pop(0))

N .append(M .pop(0))

N  =  N[- 1]

return  M,  N

L  =   [-2,0,-3]

M,  N  =  foo(L)

print(L,  M,  N)

(3)  What is the output of the following code snippet?

a  =  [1,2,3]

def  foo(l):

For  i  in  range(len(l)):

l[i]  +=   1

return   l

print(foo(a))

(4)  What is the output of the following code snippet?

import  re

r  =   ‘[^\d]’

s  =   ‘1092  abc’

x  =  re .search(r,s)

print(x .span())

Question 3: 20 points (5 points each)

Short answers

(1)  Explain the diferences between func1 and func2, which are dened below. Specically, do

they produce diferent output and if so, what are their output (e.g., diferent types or values)?

def  fib1(limit):

a  =  0

b  =  1

while  a  <   limit:

a  =  b

b  =  a  +  b

return  a

def  fib2(limit):

a  =  0

b  =  1

while  a  <   limit:

a  =  b

b  =  a  +  b

yield  a

fib1(3)

fib2(3)

(2)   Write a situation where lists are more suitable than dictionaries to store data; write another

situation where dictionaries are more suitable than lists to store data.

(3)  Name 2 advantages of using object-oriented programming (OOP) and explain them.

(4)  Write an example where you can and should use inheritance to model the objects.

(5) Circle 4 places in the following codes that you think have bad programming styles and explain

why.

def  computation(b,  c=0):

for  i  in  range(len(b)):

b[i]  =  b[i] .upper() .split() .strip() .replace(‘,’,’’)

print(b)

computation([‘a’,’b’,’abc,edf’])

Question 4: 30pt (6pt each)

Writing code snippets

If you need to get the n_th digit of an integer, you can directly call the function:

def   get_digit(number,   n):

return  number  //  10**n  %  10

(1) Write a function is_anagram(s1,   s2) that takes two strings and check if they are anagram

of  each  other. A  string  is  an  anagram  of  another  string  if  its  characters  can  be  reordered  to  be

another string . Upper cases and lower cases should be treated as the same . You should not use

sort() or sorted() . If any of the two input strings is empty, return False. Sample output: is_anagram(‘ABcd’,   ‘CbaD’)  ->  True

is_anagram(‘ECia’,   ‘abE’)  ->  False

is_anagram(‘’,   ‘’)  ->  False

(2)  Write  a  function  is_palindrome_num(n)  to  take  in  an  integer  n  and  returns  True  if  the

integer  is  a  palindrome  and  False  if  not . An  integer  is  a  palindrome  if the  digits  are still the same

after being reversed . Negative numbers should be treated as positive .   Sample output:

is_palindrome_num(12321)   ->  True

is_palindrome_num(123)  ->  False

is_palindrome_num(0)  ->  True

(3) Write a function key_with_max_val(d) to nd the key which is associated with the largest

value   in   a   dictionary   d .  The   dictionary   keys   are   strings   and   values   are   numbers .  The   input

dictionary may be empty.

key_with_max_val({‘a’:3,’c’:- 1})   ->   ‘a’

key_with_max_val({})  ->   ‘’

(4)    Write  a  recursive  function  factorial(n)  where the  input  n  is  an  integer. The  function

should return an integer that product of all integers smaller than it and greater than 0. Assume the

input n is always an integer. Sample output:

factorial(3)  ->  6,  factorial(- 1)  ->  1

factorial(0)  ->  1

Question 4 (Continued)

(5) a. (3pt) Write a function using ilter to return a list of numbers that can be divided by 5. Sample

output:

five_dividend([0,3,2,10,15])  ->   [10,15]

b. (3pt) Rewrite the following function using reduce. The input is a possibly empty list. Assume

that elements in the list are all numbers .

def  foo(l):

n  =  0

for  e  in  l:

n  +=  e

return  n

Question 5: 30pt + 10pt (bonus point)

Writing code snippets

(1)  (5pt) Write the constructor for the class Matrix that has three attributes: n_rows, n_cols,

values . For simplicity, we assume matrices here will be 2- D arrays where each element is a

number. Each matrix, if no values parameters are passed in, should be initialized to contain all

0s. A Matrix instance can be created as below. M1 has 2 rows and 3 columns.

M1  =  Matrix  (2,3,  [[1,2,3],[4,5,6]])

Assume the Matrix class also has other methods implemented that help you access data in the

matrices . For example, row(n) will return the n_th row of the matrix as a list, starting from 0.

Similarly, cols(m) will return the m_th column of the matrix as a list, starting from 0. val(n,  m)

will return the number at the n_th row and m_th column of a matrix. For example,

M1 .val(1,2)  ->  5

M1 .row(1)  ->  [4,5,6]

(2) (10pt) Implement an instance method add to add two matrices. Two matrices must have the

same number of rows and columns to be added . If their dimensions dont match, the function

should return None. The output should be a Matrix instance with the values lled in as the sum of

the two matrices . Sample method call is below. The operation of adding two matrices is illustrated

in the gure.

M1 .add(M2)

 

(3) (10pt) Implement an instance method transpose that return the transpose of a matrix. The

transpose of a matrix A is a matrix B whose rows are the columns of A. Sample output:

Suppose M1 is an instance of the Matrix class with value: [[1,2,3],[4,5,6],[7,8,9]], then

M1 .transpose()  ->  M2 where ,2 is an instance of the Matrix class with value [[1,4,7],[2,5,8],

[3,6,9]].

Question 5 (Continued)

(4) (5pt) Write the new class IdentityMatrix with its constructor. An identity matrix is a matrix

whose values  are  all  1.  Implement  a  subclass  IdentityMatrix which  inherits the  methods from the

superclass Matrix but changes the constructor to ll all 1s in the cells instead of 0s.

(6) (Bonus Point 5pt) Write an instance method multiply(Matrix   B) that multiplies two matrix

instances  of the  Matrix  class . A  matrix A  (with  a_rows  rows  and  a_cols  columns)  and  a  matrix  B

(with  b_rows  rows  and  b_cols  columns)  can  only  be  multiplied  if  their  dimensions  match  in  the

way such that a_cols =  b_rows . Otherwise, the  method should  return None. An  illustration of the

matrix multiplication works is below. You can call the method by: M1 .multiply(M2)

 

 

(7) (Bonus Point 5pt) Write an instance method is_inverse that returns True if two instances of

the  Matrix  class  are  inverse  of  each  other.  A  matrix  A  is  the  inverse  of  another  matrix  B  if  the

product of A multiplies B is an identity matrix. You can call the method by: M1 .is_inverse(M2)