...

/

Solution: Task V to Task VIII

Solution: Task V to Task VIII

The solution to the previously assigned challenges: Task V to Task VIII.

Explanation

Task 5: Add matrices in series

You were to add matrices in the order the coroutine add_series receives them.

Look at the following code.

Press + to interact
main.py
matrix.py
matrix1.txt
matrix2.txt
from matrix import Matrix
import contextlib
from functools import wraps
# Generator function decorated
@contextlib.contextmanager
def readFile(filename, mode):
myfile = open(filename, mode) # Executed before the block
yield myfile
myfile.close() # Executed after the block
# Reading matrix from file
def read_matrix(filename):
matrix = []
with readFile(filename, 'r') as fp:
for line in fp:
matrix.append([int(num) for num in line.split()])
return matrix
# Reading matrices
matrix1 = Matrix(read_matrix('matrix1.txt'))
matrix2 = Matrix(read_matrix('matrix2.txt'))
# Priming a coroutine
def coroutine(func):
@wraps(func)
def primer(*args, **kwargs):
generator = func(*args, **kwargs)
next(generator)
return generator
return primer
# Adding matrices in series
@coroutine
def add_series():
result = Matrix(None)
while True:
curr_matrix = yield result
if result.matrix is None: # First retrieval
result.matrix = curr_matrix.matrix
result.print()
else:
try:
result = curr_matrix + result # Adding previous result
except:
print('Cannot add.')
else:
result.print()
cr = add_series()
cr.send(matrix1)
cr.send(matrix2)
m = Matrix([[0,0]])
cr.send(m)
cr.send(matrix1)
cr.close()

In main, look at the header of add_series at line 39. We create a matrix result. It’s empty, initially. Look at line 43. We apply this condition because we want the process to continue until a user is sending some values. We are yielding result as this value, which will possibly change in every step. When a user sends a value, it will be stored in curr_matrix.

Now, at the time when add_series gets a ...

Access this course and 1400+ top-rated courses and projects.