gpt4 book ai didi

Create a single object from chained comparison in Python(在Python中通过链接比较创建单个对象)

转载 作者:bug小助手 更新时间:2023-10-25 15:50:33 35 4
gpt4 key购买 nike



I am toying around with chained comparison in Python, that is, something like a < b < c. According to the docs, it is evaluated as (a < b) and (b < c), where b is evaluated only once.

我正在使用Python中的链式比较,也就是类似a


I do this to save inequalities of symbolic expressions to a list. For example:

我这样做是为了将符号表达式的不等性保存到列表中。例如:


l = Keeper()
a = Symbol()
b = Symbol()
c = Symbol()
l.add(a < b)
l.add(b < c)

This works nicely. Now I've seen in the HiGHS documentation something and am baffled how they do it. Here they give this example:

这样做效果很好。现在,我在High S的文档中看到了一些东西,并对他们如何做到这一点感到困惑。这里他们给出了这个例子:


x0 = h.addVar(lb = 0, ub = 4)
x1 = h.addVar(lb = 1, ub = 7)

h.addConstr(5 <= x0 + 2*x1 <= 15)

with the implication that this means what one would expect with standard mathematic notation.

暗示着这意味着人们对标准数学记数法的期望。


How do they do it? The best I can do is create either the 5 <= x0 + 2*x1 part or the x0 + 2*x1 <= 15, but never both.

他们是怎么做到的?我最多只能创建5<=x0+2*x1部分或x0+2*x1<=15部分,但不能同时创建两者。


Any ideas?

有什么主意吗?


更多回答

maybe, as you suggest that a<b<c is unfolded as (a<b)and(b<c), you should overload the and for your Symbol class?

也许,正如您建议将a

@Sasha and can't be overloaded in Python

@sasha,并且不能在Python中重载

优秀答案推荐

Not really an answer, but I checked:

不是真正的答案,但我查了一下:


class C():
def __init__(self, value):
self.value = value

def __and__(self, y):
return C('(' + self.value + '&' + y.value + ')')

def __lt__(self, y):
return C('(' + self.value + '<' + y.value + ')')

def __bool__(self):
return self

a = C('1')
b = C('2')
c = C('3')
print((a < b < c).value)

and get:

并获得:


TypeError: __bool__ should return bool, returned C

so maybe the library you mention somehow overrides this prohibition of __bool__ returning a bool?

那么,也许你提到的库以某种方式推翻了__bool_返回bool的禁令?


更多回答

But that only turns the rich return value into a bool. It still does combine the two parts of the comparison.

但这只会让丰厚的回报变成布尔值。它仍然将比较的两个部分结合在一起。

@cxxl Yes, I said it is not an answer, it throws an error; would the compiler have allowed the code as I have written it, overlooking the return value, this would have been an answer, I believe...

@cxxl是的,我说这不是答案,它抛出一个错误;编译器会允许我编写的代码,忽略返回值,这将是一个答案,我相信...

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com