Home > other >  How to define a function that has a condition as input?
How to define a function that has a condition as input?

Time:07-17

I need a function that takes a rule/condition as an input. for example given an array of integers detect all the numbers that are greater than two, and all the numbers greater than four. I know this can be achieved easily without a function, but I need this to be inside a function. The function I would like to have is like

def _select(x,rule):    
    outp = rule(x)
    return outp    
    
L = np.round(np.random.normal(2,4,50),decimals=2)     
y = _select(x=L,rule=(>2))
y1 = _select(x=L,rule=(>4))

How should I code a function like this?

CodePudding user response:

Functions are first class objects meaning you can treat them as any other variable.

import numpy as np

def _select(x,rule):

    outp = rule(x)
    return outp

def rule_2(val):
    return val > 2

def rule_4(val):
    return val > 4

L = np.round(np.random.normal(2,4,50),decimals=2)
 
y = _select(x=L,rule=rule_2)
print(y)
y1 = _select(x=L,rule=rule_4)
print(y1)

In your example, the condition you want to use can be expressed as a simple expression. The python lambda keyword lets you define expressions as anonymous functions in other statements and expressions. So, you could replace the explicit def of the functions

import numpy as np

def _select(x,rule):

    outp = rule(x)
    return outp

L = np.round(np.random.normal(2,4,50),decimals=2)
 
y = _select(x=L,rule=lambda val: val > 2)
print(y)
y1 = _select(x=L,rule=lambda val: val > 4)
print(y1)
  • Related