In [1]:
# problem 1
import random
# warning: don't execute in here, use ipython
def random_walk(max_iters: float=1e12) -> list[int]:
walk: list[int] = []
directions = [1, -1]
i: int = 0
try:
while True:
walk += [random.choice(directions)]
i+=1
if float(i) > max_iters:
break
except KeyboardInterrupt as e:
print("Process interrupted at iteration ", e)
else:
print("Process completed")
return walk
random_walk(10)
Out[1]:
In [ ]:
# problem 2
# warning: don't execute here, use ipython if the file does not exist
class ContentFilter:
def __init__(self, given_file_name):
self.file_name = ""
self.contents = ""
try:
with open(given_file_name, "r") as f:
self.file_name = given_file_name
self.contents = f.read()
except IOError:
print("File not found. Try another name.")
while (True):
input_file_name = input()
try:
with open(input_file_name, "r") as f:
self.file_name = input_file_name
self.contents = f.read()
break
except IOError:
print("File not found. Try another name.")
content_filter = ContentFilter("foo.txt")
print("Name: {}, Contents: {}".format(content_filter.file_name, content_filter.contents))
In [1]:
# problem 3
import numpy
def multiply_matrices():
A = numpy.array([[3, -1, 4], [1, 5, -9]])
B = numpy.array([[2, 6, -5, 3], [5, -8, 9, 7], [9, -3, -2, -3]])
return A @ B
multiply_matrices()
Out[1]:
In [4]:
# problem 4
def mult_matrix_with_self():
A = numpy.array([[3, 1, 4], [1, 5, 9], [-5, 3, 1]])
return -numpy.linalg.matrix_power(A, 3) + 9*numpy.linalg.matrix_power(A, 2) - 15*A
mult_matrix_with_self()
Out[4]:
In [5]:
# problem 5
def array_creation():
A = numpy.triu(numpy.ones((7, 7)))
print(A)
B1 = -numpy.ones((7, 7))
B2 = numpy.triu(numpy.full((7, 7), 6))
B3 = numpy.eye(7) * -6
B = B1 + B2 + B3
return A @ B @ A
array_creation()
Out[5]:
In [6]:
# problem 6
def fancyZeroes(A):
B = A.copy()
B[B < 0] = 0
return B
fancyZeroes(numpy.array([[-10, 5], [-30, 20]]))
Out[6]:
In [7]:
# problem 7
def stacking():
A = numpy.array([[0, 2, 4], [1, 3, 5]])
B = numpy.array([[3, 0, 0], [3, 3, 0], [3, 3, 3]])
C = numpy.array([[-2, 0, 0], [0, -2, 0], [0, 0, -2]])
col1 = numpy.vstack((numpy.zeros((2, 3)), A, B))
col2 = numpy.vstack((A.T, numpy.zeros((2, 2)), numpy.zeros((2, 2))))
col3 = numpy.vstack((numpy.eye(3), numpy.zeros((1, 3)), C))
return numpy.hstack((col1, col2, col3))
stacking()
Out[7]:
In [8]:
# problem 8
def stochasticMat(A):
# it is a row vector when it should be column
# Equivalent: return A/A.sum(axis=1).reshape(3,1)
return A/A.sum(axis=1)[:, None]
stochasticMat(numpy.array([[2, 3],[3, 2]]))
Out[8]: