54 lines
1.5 KiB
Python
54 lines
1.5 KiB
Python
import numbers
|
|
|
|
|
|
class BetterMatrix:
|
|
def __init__(self, matrix):
|
|
zero_count = 0
|
|
self.matrix = []
|
|
self.width = len(matrix)
|
|
self.height = len(matrix[0])
|
|
|
|
for row in matrix:
|
|
for col in row:
|
|
if col == 0:
|
|
zero_count += 1
|
|
elif zero_count != 0:
|
|
self.matrix.append([zero_count])
|
|
self.matrix.append(col)
|
|
zero_count = 0
|
|
else:
|
|
self.matrix.append(col)
|
|
|
|
if zero_count != 0:
|
|
self.matrix.append([zero_count])
|
|
|
|
print(self.matrix)
|
|
|
|
def __getitem__(self, row):
|
|
if row > self.height or row < 0:
|
|
raise ValueError("Value must be between 0 and " + str(self.height - 1))
|
|
|
|
dest_array = []
|
|
dest_amount = (row + 1) * self.width
|
|
index = 0
|
|
while dest_amount > len(dest_array):
|
|
if isinstance(self.matrix[index], numbers.Number):
|
|
dest_array.append(self.matrix[index])
|
|
else:
|
|
for i in range(self.matrix[index][0]):
|
|
if dest_amount > len(dest_array):
|
|
dest_array.append(0)
|
|
index += 1
|
|
|
|
while len(dest_array) > self.width:
|
|
dest_array.pop(0)
|
|
|
|
return dest_array
|
|
|
|
|
|
converted = BetterMatrix([[3, 0, -2, 11], [0, 0, 9, 0], [0, 7, 0, 0], [0, 0, 0, -3]])
|
|
print(converted[0][0])
|
|
print(converted[1][1])
|
|
print(converted[2][2])
|
|
print(converted[3][3])
|