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 Matriximport contextlibfrom functools import wraps# Generator function decorated@contextlib.contextmanagerdef readFile(filename, mode):myfile = open(filename, mode) # Executed before the blockyield myfilemyfile.close() # Executed after the block# Reading matrix from filedef 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 matricesmatrix1 = Matrix(read_matrix('matrix1.txt'))matrix2 = Matrix(read_matrix('matrix2.txt'))# Priming a coroutinedef coroutine(func):@wraps(func)def primer(*args, **kwargs):generator = func(*args, **kwargs)next(generator)return generatorreturn primer# Adding matrices in series@coroutinedef add_series():result = Matrix(None)while True:curr_matrix = yield resultif result.matrix is None: # First retrievalresult.matrix = curr_matrix.matrixresult.print()else:try:result = curr_matrix + result # Adding previous resultexcept: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.