Question
Complete the function sparse_matrix in the t05_functions.py module. The module t05.py provides simple testing for this function. A sparse matrix is a matrix that typically
Complete the function sparse_matrix in the t05_functions.py module. The module t05.py provides simple testing for this function.
A sparse matrix is a matrix that typically is very large but contains very little non-zero data. Rather than store the zeroes the sparse matrix stores the row and column location of only the non-zero values. This function converts a file, where each line of the file represents a row in the resulting matrix, into a 2D Python list whose contents are of the form:
[[row, col, value], [row, col, value], ...]
The sample file sparse1.txt contains:
0,0,0,0,0,0,0,0,6,0,0 0,0,0,9,0,0,0,0,0,0,0 0,2,0,0,0,0,0,4,0,0,0 0,0,0,0,0,0,7,0,0,0,0
which becomes:
[[0, 8, 6], [1, 3, 9], [2, 1, 2], [2, 7, 4], [3, 6, 7]]
Thus: [0, 8, 6] is row 0, column 8, value 6; [1, 3, 9] is row 1, column 3, value 9; etc.
Some examples from executing t05.py against sparse2.txt and sparse3.txt:
f_in = open('sparse2.txt', "r", encoding="utf-8") matrix = sparse_matrix(f_in) fh_in.close()
[]
f_in = open('sparse3.txt', "r", encoding="utf-8") matrix = sparse_matrix(f_in) fh_in.close()
[[0, 0, 12], [0, 1, 13], [0, 2, 14]]
Requirements
This function must:
Return, not print, the resulting 2D list
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started