forked from course-work/week1
Update 04-matrix-sort/row_col_sort.py
This commit is contained in:
parent
5100753526
commit
b7133f3362
@ -0,0 +1,52 @@
|
||||
def matrix_parse(matrix):
|
||||
out = []
|
||||
for row in matrix.split('\n'):
|
||||
out.append([int(col) for col in row.split()])
|
||||
|
||||
return out
|
||||
|
||||
def matrix_sum(matrix):
|
||||
row_sum = []
|
||||
col_sum = [0 for col in range(len(matrix)+1)]
|
||||
|
||||
for row in matrix:
|
||||
row_sum.append(sum(row))
|
||||
for idx, col in enumerate(row):
|
||||
col_sum[idx] += col
|
||||
|
||||
return row_sum, col_sum
|
||||
|
||||
def matrix_get_element_width(matrix):
|
||||
max = 0
|
||||
for row in matrix:
|
||||
for element in row:
|
||||
if max < len(str(element)):
|
||||
max = len(str(element))
|
||||
|
||||
return max
|
||||
|
||||
def matrix_print(matrix, width=None):
|
||||
if not width:
|
||||
return matrix_print(matrix, matrix_get_element_width(matrix))
|
||||
|
||||
for row in matrix:
|
||||
print('', *['{:{}d}'.format(el, width) for el in row], '', sep=' | ')
|
||||
|
||||
def matrix_from_file(file):
|
||||
with open(file, 'r') as file:
|
||||
|
||||
return matrix_parse(file.read())
|
||||
|
||||
|
||||
m1 ='''10 5 4 20
|
||||
9 33 27 16
|
||||
11 6 55 3'''
|
||||
|
||||
# m1 = matrix_parse(m1)
|
||||
# print(m1)
|
||||
# print(matrix_sum(m1))
|
||||
# print(matrix_get_element_width(m1))
|
||||
# matrix_print(m1)
|
||||
|
||||
m2 = matrix_from_file('./matrix.txt')
|
||||
print(matrix_sum(m2))
|
Loading…
x
Reference in New Issue
Block a user