有没有办法根据某些布尔值在逻辑运算符之间进行交换?

Is there a way to swap between logical operators on the basis of some boolean?

我正在实现一个括号函数来练习。该函数将查明一个范围,在该范围内发生某个函数的最小值或最大值。

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

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

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 module.

将比较运算符表示为函数

例如表达式 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