简体   繁体   English

创建一个能够根据给定参数生成函数对象(在这种情况下为分段函数)的脚本

[英]Creating a script capable of generating function objects (piecewise functions in this case) from given parameters

I was wondering what is the best way to do the following. 我想知道什么是执行以下操作的最佳方法。 Consider a piecewise function which takes on constant values for different ranges. 考虑一个分段函数,该分段函数在不同范围内采用恒定值。 For example: from t = 0 to t = 2 , x = 3 and from t = 2 to t = 4, x = 1. I define a piecewise function by the following parameters: 例如:从t = 0到t = 2,x = 3,从t = 2到t = 4,x =1。我通过以下参数定义分段函数:

  • list of x, eg [3,3,1,1,1] x的列表,例如[3,3,1,1,1]

or 要么

  • two lists which generate a list of x. 两个生成x列表的列表。 The example above is generated by [3,1] (values of x) and [2,3] (how often they are repeated). 上面的示例由[3,1](x的值)和[2,3](重复的频率)生成。

From this, I want the script to create the following function, using the example above: 由此,我希望脚本使用上面的示例创建以下函数:

def function(x):
    if 0 <= x < 2:
        return 3
    if 2 <= x <= 4:
        return 1

Thus I need some method that will take in either the list of x values or the list of x and how often they are repeated to create a function of x: 因此,我需要某种方法将采用x值列表或x列表,以及将它们重复创建一个x函数的频率:

def function(x)
    if bound1 <= x < bound2:
        return x1
    if bound2 <= x < bound3: 
        return x2
    if bound3 <= x < bound4:
        return x3

    ...

    if bound_n-1 <= x < bound_n:
        return x_n

I've been reading on classes and function wrapping but I'm still slightly unsure as to what would be the best solution for this problem. 我一直在阅读类和函数包装,但是我仍然不确定什么是解决此问题的最佳方法。

Thanks 谢谢

Maybe you should look at bisect.bisect_right function ( official doc ): 也许您应该看一下bisect.bisect_right函数( 官方文档 ):

from bisect import bisect_right
from functools import partial

# <0, 2) -> 3
# <2, 4) -> 1
# <4, 6) -> 99
bounds          = [0, 2, 4, 6]
return_values   = [3, 1, 99]

def fn(val, bounds, return_values):
    i = bisect_right(bounds, val) - 1
    return return_values[i] if i < len(return_values) else None

# function(x)
function = partial(fn, bounds=bounds, return_values=return_values)

print(function(0))
print(function(1))
print(function(2))
print(function(3))
print(function(4))
print(function(5))
print(function(6))

Prints: 打印:

3
3
1
1
99
99
None

Edit: Updated answer to call the function() just with one parameter. 编辑:更新了答案,仅用一个参数即可调用function()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM