Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a function that has a condition as input?

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?

like image 923
Gaetano Veti Avatar asked Nov 29 '25 01:11

Gaetano Veti


1 Answers

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)
like image 142
tdelaney Avatar answered Dec 01 '25 14:12

tdelaney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!