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

Asked

Viewed 92 times

-1

Find the first line in the matrix with all positive elements, and the sum of these elements. Reduce all elements to that 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.")
  • 1

    I didn’t quite understand what your question was, could you write in your words? What error is giving in your code?

  • Downvote because it’s homework.

2 answers

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]]

0

That solves?

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.");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.