Reference no: EM132197714
Part A) Arrays and copy semantics Consider the following Python code segment, which uses built-in Python lists and NumPy lists to perform similar operations, albeit with differing results.
Using built-in Python lists:
>>> data = [1, 2, 3, 4]
>>> print data [1, 2, 3, 4]
>>> otherData = data
>>> otherData[1] = -2
>>> print otherData [1, -2, 3, 4]
>>> print data [1, -2, 3, 4]
>>>
>>> otherData = data[1:3]
>>> print otherData [-2, 3]
>>> otherData[0] = 0
>>> print otherData [0, 3]
>>> print data Using NumPy arrays:
>>> import numpy as np
>>> data = np.array([1, 2, 3, 4])
>>> print data [1 2 3 4]
>>> otherData = data
>>> otherData[1] = -2
>>> print otherData [1 -2 3 4]
>>> print data [1 -2 3 4]
>>>
>>> otherData = data[1:3]
>>> print otherData [-2 3]
>>> otherData[0] = 0
>>> print otherData [0 3]
>>> print data [1 0 3 4]
Describe similarities and differences between copying and assignment semantics of built-in Python lists and NumPy arrays. Explain why the code behaves differently for the two.
Part B) Matrices NumPy also supports matrices. However, there are some important differences between two-dimensional arrays and matrices. Consider the following two code segments that are similar, but produce different results: Using NumPy two-dimensional arrays:
>>> A = np.array([[1,2], [3,4]])
>>> B = np.array([[2,1], [-1,2]])
>>> A * B array([[ 2, 2], [-3, 8]])
>>> A ** 3 array([[ 1, 8], [27, 64]])
Using NumPy matrices:
>>> A = np.matrix([[1,2], [3,4]])
>>> B = np.matrix([[2,1], [-1,2]])
>>> A * B matrix([[ 0, 5], [ 2, 11]])
>>> A**3 matrix([[ 37, 54], [ 81, 118]])
Describe similarities and differences between NumPy two-dimensional arrays and matrices. Explain why the code behaves differently for the two.