Python Concepts/Quizzes/NumPy & Co.

From Wikiversity
Jump to navigation Jump to search

1 With the follow code

a = range(2,9)
map(lambda x, y: x ** y, a, reversed(a))

choose one or more of the following:

True False
The first element in the result is 2

2 With the above code

True False
The map function iterates over two lists/iterators.

3 With the above code

True False
The first input argument to the "map" function is a function itself

4 With the above code

True False
The last element of the result is 92=81

5 With the follow code

import numpy as np

A = np.matrix([[1, 2], [3, 4]])
B = np.mat([[5, 6], [5, 6]])

B is:

An ordinary list (of lists) Python object: <type 'list'>
A numpy array
A numpy matrix

6 With the above code and

A * B

the result is

A matrix product
matrix([[15, 18], [35, 42]])
An elementwise product of the matrix elements:
array([[ 5, 12], [15, 24]])
TypeError: can't multiply sequence by non-int of type 'list'
Concatenation of the two lists

7 With the following code

import numpy as np
import numpy.linalg

A = np.mat([[2, 1], [1, 2]])
B = numpy.linalg.inv(A)
A * B

the result is

matrix([[ 1.,  0.], [ 0.,  1.]])
matrix([[0, 1], [1, 0]])
matrix([[-5, -4], [-4, -5]])
matrix([[5, 4], [4, 5]])

8 With the following code

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 1000)
plt.plot(x, np.sin(x) + x)

the result is

An error as "np.sin" only works for a single value
A plot with 1000 elements
A plot with 2000 elements as "np.sin(x)" and "x" is concatenated

9 With the following code

# Import simplex algorithm
from scipy.optimize import fmin
import numpy as np

def f(x):
    return (x[0]-3)**2 + 3*x[0] - 2*x[1] + x[1]**2

fmin(f, np.random.rand(2))

the result is

Two random values between 0 and 1
approximately array([ 1.50000971, 0.99996545])
approximately array([ 1.24996107])
The minimum of two random numbers and the value of the function

10 With the following code

import scipy.stats
import numpy as np

# Get an instance of class for the Gaussian distribution (also called normal distribution)
gaussian = scipy.stats.norm(loc=10, scale=3)

# Generate 1000 random samples
data = gaussian.rvs(1000)

# Insert a "not a number" value in the 11th element
data[10] = np.nan

# Compute the mean
m = scipy.stats.nanmean(data)

"m" is

approximately 10