有没有一种方法可以在一些布尔值的基础上在逻辑运算符之间进行交换



我正在实现一个用于练习的括号函数。该函数将精确定位某个函数的最小值或最大值之间的范围。

为了提供标识最小值或最大值的选项,我允许用户传递布尔值findMin。

以下代码块标识最小值;此块与标识最大值的块之间的唯一区别是,比较运算符("<"one_answers">")必须相互交换。我可以通过插入一个相同的代码块(但对于交换的比较运算符)来轻松地进行交换,该代码块由if语句处理,该语句只有在用户想要找到最大值时才输入。在不必添加另一个这样的代码块的情况下,有没有一种方法可以交换比较运算符"<"one_answers">"?

def bracket (func, x, findMin, stepSize = 0.001):
    # Determine which direction is downward
    increment = 0.001
    if func(x+stepSize) > func(x):
        stepSize *= -1
        increment *= -1
    pointer = x + stepSize
    previousPointer = x
    while(func(pointer) < func(previousPointer)):
        previousPointer = pointer
        pointer += stepSize
        stepSize += increment
    a = min(pointer, previousPointer)
    b = max(pointer, previousPointer)
    return a,b

在python中,您可以使用operator模块将比较运算符表示为函数。

例如,表达式1 > 2等同于调用operator.gt(1, 2)

这是一种将其传递给函数的方法:

import operator
def test(arg1, arg2, compare_function):
    if compare_function(arg1, arg2):
        print("condition is true")
    else:
        print("condition is false")

输出:

>>> test(1, 2, operator.lt)
condition is true
>>> test(1, 2, operator.gt)
condition is false

您可以使用类:

Operator    Method
 ==        __eq__()
 !=        __ne__()
 >         __gt__()
 >=        __ge__()
 <         __lt__()
 <=        __le__()

例如:

class foo(object):
    """It's fun to override """
    def __init__(self, name):
        self.name=name
    def __gt__(self, other):
        # Write your logic  here ...
        return self.name < other.name

现在你可以比较它们:

In [2]: g = foo(6)
In [3]: y = foo(4)
In [4]: g>y
Out[4]: False
In [5]: g<y
Out[5]: True

最新更新