How do I write a function that replaces all negative numbers in an array with a 0.
Here is what I have so far:
def negativesToZero(A):
for x in A:
if x < 0:
A.append(0)
else:
pass
print A
A = ([[1,-2],\
[-2,1]])
negativesToZero(A)
Since A is a list of lists:
>>> A = [[1, -2], [-2, 1]]
>>> for lst in A:
... for i, val in enumerate(lst):
... lst[i] = max(val, 0)
>>> print A
[[1, 0], [0, 1]]
Alternatively using list comprehensions:
>>> A = [[max(val, 0) for val in lst] for lst in A]
If you want an array operation, you should create a proper array to start with.
A=array([[1,-2],[-2,1]])
Array comprehensions like yours can be one-lined using boolean operations on indices:
A[A<0]=0
Of course you can frame it as a function:
def positive_attitude(x):
x[x<0]=0
return x
print positive_attitude(A)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With