|
| 1 | +# The file matrix.txt contains a matrix in the format specified in the example below: |
| 2 | + |
| 3 | +# 1,0,2,8,2,1,3,2,5,2,2,2 |
| 4 | +# 9,2,4,5,2,4,2,4,1,10,4,2 |
| 5 | +# ...etc... |
| 6 | +# Please write two functions, named matrix_sum and matrix_max. |
| 7 | +# Both go through the matrix in the file, and then return the sum of the elements or the element with the greatest value, as the names of the functions imply. |
| 8 | + |
| 9 | +# Please also write the function row_sums, which returns a list containing the sum of each row in the matrix. |
| 10 | +# For example, calling row_sums when the matrix in the file is defined as |
| 11 | + |
| 12 | +# 1,2,3 |
| 13 | +# 2,3,4 |
| 14 | + |
| 15 | +# the function should return the list [6, 9]. |
| 16 | + |
| 17 | +# Hint: you can also include other helper functions in your program. |
| 18 | +# It is very worthwhile to spend a moment considering which functionalities are shared by the three functions you are asked to write. |
| 19 | +# Notice that the three functions named above do not take any arguments, but any helper functions you write may take arguments. |
| 20 | +# The file you are working with is always named matrix.txt. |
| 21 | + |
| 22 | +def open_matrix(): |
| 23 | + with open("matrix.txt") as new_file: |
| 24 | + matrix = [] |
| 25 | + for line in new_file: |
| 26 | + int_row = [] |
| 27 | + line = line.replace("\n","") |
| 28 | + line = line.split(",") |
| 29 | + for value in line: |
| 30 | + int_row.append(int(value)) |
| 31 | + matrix.append(int_row) |
| 32 | + return matrix |
| 33 | + |
| 34 | +def row_sums(): |
| 35 | + matrix = open_matrix() |
| 36 | + sum_rows = [] |
| 37 | + for row in matrix: |
| 38 | + sum_rows.append(sum(row)) |
| 39 | + return sum_rows |
| 40 | + |
| 41 | +def matrix_sum(): |
| 42 | + row_sum = row_sums() |
| 43 | + return sum(row_sum) |
| 44 | + |
| 45 | +def matrix_max(): |
| 46 | + matrix = open_matrix() |
| 47 | + max_value = matrix[0][0] |
| 48 | + for row in matrix: |
| 49 | + if max(row) > max_value: |
| 50 | + max_value = max(row) |
| 51 | + return max_value |
0 commit comments