Skip to Main Content
Blog

Create Sparse Matrix in Python

Create Sparse Matrix in Python

def main():
	"""
	Prints the sparse representation of a matrix.
	"""

	row = int(input("Enter row length: "))
	col = int(input("Enter col length: "))
	print("Enter matrix:")
	mat = read_matrix(row, col)

	res = sparse(mat)
	print_matrix(res)


def sparse(matrix: list[list[int]]):
	"""
	Converts a matrix to a sparse matrix.
	"""

	m = len(matrix)
	n = len(matrix[0]) if m > 0 else 0

	# Count the number of non-zero elements
	zeroCount = sum(1 for r in range(m) for c in range(n) if matrix[r][c] != 0)

	# Make sure the matrix is actually sparse
	if (1 + zeroCount) * 3 >= m * n:
		raise ValueError("Matrix is not sparse.")

	# Create the sparse matrix and store dimensions
	sparse_matrix = [[m, n, zeroCount]]

	# Store the non-zero elements in the matrix
	for r in range(m):
		for c in range(n):
			if matrix[r][c] != 0:
				sparse_matrix.append([r, c, matrix[r][c]])

	return sparse_matrix


def read_matrix(row_count: int, col_count: int):
	"""
	Reads a matrix from the console.
	"""

	matrix: list[list[int]] = []
	for _ in range(row_count):
		row = list(map(int, input().split()[:col_count]))
		matrix.append(row)

	return matrix


def print_matrix(matrix: list[list[int]]):
	"""
	Prints a matrix to the console.
	"""

	for row in matrix:
		for element in row:
			print(element, end=" ")
		print()


if __name__ == "__main__":
	main()