Advertisement
Nenogzar

test_square

May 22nd, 2024
496
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. def calculate_columns(matrix):
  2.     columns = max(len(row) for row in matrix)
  3.     return columns
  4.  
  5. def check_valid_index(row, col, rows, columns):
  6.     return row + 1 < rows and col + 1 < columns
  7.  
  8. def sum_square(matrix, row, col):
  9.     sum_total = 0
  10.     for r in range(row, row + 2):
  11.         for c in range(col, col + 2):
  12.             sum_total += matrix[r][c]
  13.     return sum_total
  14.  
  15. def find_max_sum(matrix):
  16.     max_sum = {"max number": float('-inf'), "row": 0, "col": 0}
  17.     rows = len(matrix)
  18.     columns = calculate_columns(matrix)
  19.  
  20.     for row in range(rows - 1):
  21.         for col in range(columns - 1):
  22.             current_sum = sum_square(matrix, row, col)
  23.             if current_sum > max_sum["max number"]:
  24.                 max_sum["max number"] = current_sum
  25.                 max_sum["row"] = row
  26.                 max_sum["col"] = col
  27.  
  28.     return max_sum
  29.  
  30. def print_submatrix(matrix, max_sum):
  31.     row, col = max_sum["row"], max_sum["col"]
  32.     for r in range(row, row + 2):
  33.         print(" ".join(map(str, matrix[r][col:col + 2])))
  34.  
  35. def main():
  36.     matrix = []
  37.     while True:
  38.         row_input = input("Въведи ред, числа раздлени със запетая или празен за край на вход: ")
  39.         if not row_input:
  40.             break
  41.         row_values = list(map(int, row_input.split(", ")))
  42.         if matrix:
  43.             padding = max(map(len, matrix)) - len(row_values)
  44.         else:
  45.             padding = 0
  46.         matrix.append(row_values + [0] * padding)
  47.  
  48.     max_sum = find_max_sum(matrix)
  49.     print_submatrix(matrix, max_sum)
  50.     print("Max sum:", max_sum['max number'])
  51.  
  52. if __name__ == "__main__":
  53.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement