transform 1d array to a 2d matrix (cagie coding challenge)
#659
- Author
- socdev
- Created
- Jan. 16, 2023, 2:09 a.m.
- Expires
- Never
- Size
- 975 bytes
- Hits
- 35
- Syntax
- Python
- Private
- ✗ No
# import numpy as np
def make_matrix(array, row_count, column_count):
# make sure dimensions valid
if row_count * column_count != len(array):
raise ValueError("Invalid matrix size: dimensions are invalid")
ret = []
idx = 0
for i in range(row_count):
a_row = []
for j in range(column_count):
a_row.append(array[idx])
idx = idx + 1
ret.append(a_row)
return ret
# return array.reshape(n, m)
if __name__ == "__main__":
# using NumPy to help transform numbers if you do maths stuff
# arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
# vanilla stuff
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
my_matrix = make_matrix(arr, 3, 4)
print(f"Original flat(1 dimension) matrix was: {arr}\n")
print(
f"Function make_matrix instructed with n and m values made this matrix:\n {my_matrix}")