Find the first row in the matrix with all the positive elements, and the sum of these elements. Reduce all elements to this sum

-2

Find the first line in the array with all the positive elements, and the sum of these elements. Reduce all elements to this sum.

Here is my attempt, but in this way add up the positive elements:

matrix = [[-5, -6, 2], [7, 2, 3], [8, 4, -9]]

summ = 0
for i in range(len(matrix)):
    pos = False
    for j in range(len(matrix[i])):
        if matrix[i][j] > 0:
            pos = True
            summ += matrix[i][j]

if pos:
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            matrix[i][j] = summ
    print("Sum of the row with all positive elements: ", summ)
    for i in matrix:
        print(" ",i)

else:
    print("There is not a row with all positive elements.")
    
asked by anonymous 10.01.2016 / 16:46

2 answers

0

Does this solve?

sum = 0;
pos = False;

for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        if matrix[i][j] > 0:
           pos = True;
           sum+=matrix[i][j];
        else
           pos = False;
           sum = 0;
           break;
    if pos:
       break;

if pos:
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            matrix[i][j] = sum;
    print('Sum of the row with all positive elements: ',sum);
    for i in matrix:
        print(' ',i);
else:
  print("There is not a row with all positive elements.");
    
17.01.2016 / 01:14
0
>>> matrix = [[-5, -6, 2], [7, 2, 3], [8, 4, -9]]
>>> matrix
[[-5, -6, 2], [7, 2, 3], [8, 4, -9]]
>>> for line in matrix:
...  if not [i for i in line if i<0]:
...   soma = sum(line)
...   print 'Soma:',soma
...   print 'Linha:',line
...   matrix = [[soma for i in l] for l in matrix]
...   break
... 
Soma: 12
Linha: [7, 2, 3]
>>> matrix
[[12, 12, 12], [12, 12, 12], [12, 12, 12]]
    
14.04.2016 / 19:32