Write a function to calculate the sum of the matrix elements located below the main diagonal. With its help, find the maximum value of such a sum (function) in N matrices of random numbers

import random n = int (input ('введіть n=')) m = int (input ('введіть m=')) a = [] for i in range (n): a.append ([]) for j in range(m): a[i].append (random.randint(-5,5)) 
  • 3
    give an example of the code with which problems arise - Hekumok
  • I can't write anything beyond the two-dimensional matrix code - Katya
  • import random n = int (input ('enter n =')) m = int (input ('enter m =')) a = [] for i in range (n): a.append ([]) for j in range (m): a [i] .append (random.randint (-5,5)) - Katya
  • You need to add code to the text of the question, and not in the comments, where it is completely unreadable. - Enikeyschik Nov.

1 answer 1

You can do this:

 from random import randint def gen_matrix(rows, cols, min_val=0, max_val=10): return [[randint(min_val, max_val) for _ in range(cols)] for _ in range(rows)] def sum_under_diag(m): r = 0 for i, row in enumerate(m): for j, el in enumerate(row): if i > j: r += el return r N = 5 ms = [gen_matrix(rows=4, cols=4, min_val=-5, max_val=5) for _ in range(N)] res = sum_under_diag(max(ms, key=sum_under_diag)) 

Check:

 In [283]: ms Out[283]: [[[5, -3, -3, -5], [2, -4, -3, 5], [5, 4, 4, 5], [1, 1, 0, -5]], [[-5, 4, -2, 4], [4, 2, 0, -3], [1, 5, -4, -3], [-3, 3, -1, -2]], [[3, -1, 5, -5], [2, 0, -3, -3], [4, -3, -1, 0], [-3, -1, -5, 4]], [[-3, -5, 5, -2], [4, 4, 5, 2], [-1, -1, -2, -1], [1, 1, 5, 3]], [[-2, 2, 0, -2], [2, 3, 5, -4], [0, 2, 0, -1], [3, -1, 3, 2]]] In [284]: [sum_under_diag(m) for m in ms] Out[284]: [13, 9, -6, 9, 9] In [285]: max(ms, key=sum_under_diag) Out[285]: [[5, -3, -3, -5], [2, -4, -3, 5], [5, 4, 4, 5], [1, 1, 0, -5]] In [286]: sum_under_diag(max(ms, key=sum_under_diag)) Out[286]: 13