...

/

Solution: Task I to Task IV

Solution: Task I to Task IV

The solution to the previously assigned challenges: Task I to Task IV.

Brace yourself, it’s time to cover each task turn by turn to work out the project in a systematic manner. You can run each executable and verify the answers for different values.

Explanation

Task 1: Read matrix from a file

You were to read the matrix from a file using the context manager protocol, save it in the nested list, and create a Matrix object out of it.

Look at the code below.

Press + to interact
main.py
matrix.py
matrix1.txt
matrix2.txt
from matrix import Matrix
import contextlib
# 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'))

Look at the files matrix1.txt and matrix2.txt. They both contain a matrix.

Now, look at main. At line 17, we are opening the file using the readFile generator decorated by @contextmanager. The file is opened before stepping into the with-block. So, we opened the file before yield. Then, at line 9, we yielded the generator. We read each line.

See line 19. The format of the text file allows us to split the line into a list, with whitespace as a separator, by using the split() function. So, each line is treated as a row, and each value in the row stands in a column. We append each line (list) in a standard list matrix, and return it after the whole file is read.

At line 25 and line 26, we are sending matrices ...

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