Janys02
Janys02

Reputation: 31

Remove negative numbers from a matrix

I'm trying to replace all the negative numbers in the matrix with their positive equivalents. My problem is that adding them again in the for loop always skips the middle value and I don't know how to iterate through the for loop again.

I tried using a while loop but didn't get to a solution.
You can find my code so far here:

def replaceNegatives (matrix):
    for i in range(len(matrix)):
        for num in matrix[i]:
            while num < 0:
                if num < 0:
                    matrix[i].remove(num)
                    num = num * -1
                    matrix[i].append(num)

    return matrix


testMatrix = [[-4, -7, -9], [-2, -4, -6], [2, 4, -5]]
print(replaceNegatives(testMatrix))

Prints:

[[-7, 4, 9], [-4, 2, 6], [2, 4, 5]]

Upvotes: 0

Views: 406

Answers (1)

Leonid Mednikov
Leonid Mednikov

Reputation: 973

So if you want to change negative values to positive:

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

test_matrix = [[-4, -7, -9], [-2, -4, -6], [2, 4, -5]] 
replace_negatives(test_matrix)
print(test_matrix)

And it is important to understand that you this code changes the original matrix. So if this is what you want, it is common behaviour to return nothing to emphasise, that the new result is in the original place, not in the return value.

P.S. The construction *= -1 means to multiply by -1 and assign no the original value, so it is a short version of matrix[i][j] = -1 * matrix[i][j]

Upvotes: 1

Related Questions