Home > Back-end >  Returning a function acting on an array
Returning a function acting on an array

Time:01-27

Consider a function getf taking a numpy array a and integer b. I want to return a callable function f such that f has value 0 for a< b and a>b and value 1 for a=b.

Something like

  getf(a,b):
     if a< b & b>a:
         return 0 
     else:
         return 1

does not work.

How do I can ensure that my return value is a function?

Example

 a = [1,2,3,4,5]
 b=2

return function with result array [0,1,0,0,0]

CodePudding user response:

I don't understand why you need this, but this code defines a function and returns it, which can be called with two keyword arguments.

def  getf():
    def f(a, b):
        return [int(b==i) for i in a]
        
    return f
    
print(getf()(a = [1,2,3,4,5], b=2))

CodePudding user response:

You need to use vectorial code, not return a scalar. Also, use a numpy array for a.

Finally, your conditions were incorrect (you had twice the same condition). I imagine you want to check if a is greater of equal b and lower or equal b (which is a == b, but let's keep it like this for the sake of the example).

def getf(a,b):
    return ((a >= b) & (b >= a)).astype(int)

a = np.array([1,2,3,4,5])
b = 2

getf(a, b)
# array([0, 1, 0, 0, 0])
  •  Tags:  
  • Related