week1/04-matrix-sort/row_col_sort_class.py

81 lines
1.7 KiB
Python

class Matrix:
def __init__(self, **kwargs):
if kwargs.get('file'):
self.matrix = self.__from_file(kwargs['file'])
elif kwargs.get('text'):
self.matrix = self.__parse(kwargs['text'])
elif kwargs.get('matrix'):
self.matrix = kwargs['matrix']
def __from_file(self, file):
with open(file, 'r') as file:
return self.parse(file.read())
def __parse(self, matrix):
out = []
for row in matrix.split('\n'):
out.append([int(col) for col in row.split()])
return out
@property
def sum(self):
row_sum = []
col_sum = [0 for col in range(len(self.matrix)+1)]
for row in self.matrix:
row_sum.append(sum(row))
for idx, col in enumerate(row):
col_sum[idx] += col
return row_sum, col_sum
@property
def sort_row(self):
row_sum, col_sum = self.sum
out = []
for index, row in sorted( [i for i in enumerate(row_sum)], key=lambda x:x[1]):
out.append(self.matrix[index])
return Matrix(matrix=out);
@property
def sort_col(self):
row_sum, col_sum = self.sum
out = []
places = sorted( [i for i in enumerate(col_sum)], key=lambda x:x[1])
for index, row in enumerate(self.matrix):
out.append([row[i[0]] for i in places])
return Matrix(matrix=out)
def __get_element_width(self):
max = 0
for row in self.matrix:
for element in row:
if max < len(str(element)):
max = len(str(element))
return max
def __str__(self, width=None):
width = self.__get_element_width()
out = ''
for row in self.matrix:
out +=' | '.join(['{:{}d}'.format(el, width) for el in row])
out += '\n'
return out
m1 ='''10 5 4 20
9 33 27 16
11 6 55 3'''
m1 = Matrix(text=m1)
# print(m1.sum)
print(m1.sort_row)
print(m1.sort_col)