3

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)
2
  • 2
    Grab a pencil and paper and go through this code by hand. You'll find that it does some strange things that you didn't want. Commented Aug 20, 2015 at 0:16
  • This works for 2 dimensional int lists such as A: [list(map(lambda x: x if x >= 0 else -x,a)) for a in A] Commented Aug 20, 2015 at 0:30

6 Answers 6

4

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

Go through each sublist in the list. For each sublist, create a new one that turns any negative items into 0. The tidiest way is with a comprehension:

A = [[1,-2], [-2,1]]
A = [[item if item >= 0 else 0 for item in l] for l in A]

Result:

[[1, 0], [0, 1]]

Comments

0

Here is a recursive implementation that will work with any type of list, with any type of input in it:

def convertToZero(arr):
    for i in range(len(arr)):
        if type(arr[i]) == int and arr[i] < 0:
            arr[i] = 0
        elif type(arr[i]) == list:
            convertToZero(arr[i])
    return arr

result = convertToZero( [[1,-2], ['hello',[-2,1]], [-1,'world']] )
print result
# [[1, 0], ['hello', [0, 1]], [0, 'world']]

Comments

0

Here is a simple and easy to understand answer along the lines of what you were trying to do in the beginning:

def negativesToZero(A):
    index  = 0 #Track your index

    for x in A:
        if isinstance(x, list): #Calling the program recursively on nested lists
            A[index] = negativesToZero(x)

        elif x < 0:
            A[index] = 0 #Makes negatives 0

        else:
            pass #Ignores zeros and positives

        index += 1 #Move on to next index
    print A
    return A

If you don't want the unwanted inner print statements you can add an input variable (I will call it 'recur') to the function that makes only the non recursive call print:

def negativesToZero(A, recur = False):
  index  = 0

  for x in A:
    if isinstance(x, list):
      A[index] = negativesToZero(x, True)

    elif x < 0:
      A[index] = 0

    else:
      pass

    index += 1
  if recur == False: print A
  return A 

Result:

A = ([[1,-2],\
     [-2,1],\
     [-5, -6], [4,7]])

negativesToZero(A)

>>>> [[1, 0], [0, 1], [0, 0], [4, 7]]

Comments

0
import numpy as np

listOnums = np.random.normal(size = 300)
listOnums = listOnums.reshape(3,10,10)


def negToZero(arrayOnums):
    '''
    Takes an array of numbers, replaces values less than 0 with 0
    and retuns an array of numbers.
    '''
    dims = arrayOnums.shape
    flatNums = arrayOnums.flatten()

    for num,x in enumerate(flatNums):

        if x >= 0: pass
        else:
            flatNums[num] = 0

        arrayOnums = flatNums.reshape(dims)

    return arrayOnums

negToZero(listOnums) 

1 Comment

Hope this is clearer if I spell it out but for loop can absolutely be replaced with list comprehension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.