Home > Blockchain >  Negative items in matrix replaced
Negative items in matrix replaced

Time:11-24

Here is the given piece of assignment code:

Write a procedure replace_negatives(matrix), which receives a matrix with integer items as an argument.

The function replaces all negative items in the matrix with their absolute values (for example -1 is replaced with 1 and -7 with 7).


def test():

   m = []
   size = random.randint(4,7)
   for i in range(size):
       m.append([0] * size)
       for j in range(size):
           m[i][j] = random.randint(-10,10)
   print ("Matrix before:")
   output_matrix(m)
   print ("")
   
   replace_negatives(m)
   print ("Matrix after:")
   output_matrix(m)
   
def output_matrix(m):

   for row in m:
       print (row)
       
test()



import random



# next line generates a random number
# and assigns it to variable n1
n1 = random.randint(50,150) 

This is what I did:

def replace_negatives(matrix):
    

    for i in range(len(matrix)):
        if matrix[i] < 0:
             matrix[i] = matrix[i] * (-1)
             
             return(matrix)

but it gives me:

  line 43, in
    test()
  File "/tmp/untrusted/test095033c3f-464a-4fb4-8a1d-ddd8385d21a7/test.py", line 35, in test
    replace_negatives(m)
  File "/tmp/untrusted/test095033c3f-464a-4fb4-8a1d-ddd8385d21a7/test.py", line 18, in replace_negatives
    if matrix[i] < 0:
TypeError: '<' not supported between instances of 'list' and 'int'

CodePudding user response:

You are not indexing the matrix correctly. matrix[i] refers to the ith row in matrix.

for i in range(len(matrix)):
    for j in range(len(matrix)):
        if matrix[i][j] < 0:
            matrix[i][j] = abs(matrix[i][j])

The above code will work for square matrices, however, you can change the inner loop to get the number of columns.

CodePudding user response:

You can simply do :

matrix = np.absolute(matrix)
  • Related