I need to create a function which can take an unspecified number of parameters (elements for the matrix) and return the corresponding square matrix. I have implemented this using the following approach.
def square_matrix(size, *elements):
numbers = list(elements)
if size ** 2 != len(numbers):
return "Number of elements does not match the size of the matrix"
else:
matrix = []
factor = 0
for i in range(0, size):
row = []
for j in range(factor * size, (factor + 1) * size):
row.append(numbers[j])
factor += 1
matrix.append(row)
i += 1
return matrix
print(square_matrix(3, 1, 2, 3, 4, 5, 6, 7, 8, 9))
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Although this method works fine for smaller matrices, it seems somewhat inefficient as it uses nested loops and appears unnecessarily long to me. Is there any better/concise way of implementing the same?