简体   繁体   English

如何组合两个布尔 lambda 函数来创建一个新的布尔 lambda 函数?

[英]How to combine two boolean lambda functions to make a new boolean lambda function?

I encountered another problem while making this "infinite"我在制作这个“无限”时遇到了另一个问题

class Infset:
    def __init__(self, f):
        self.f = f
        
    def __or__(self, other):
        return Infset(self.f or other.f)

    def __and__(self, other):
        return Infset(self.f and other.f)

So far the class function takes in a boolean lambda function as an object.到目前为止,类函数接受一个布尔 lambda 函数作为对象。 and I have to make methods that will give the union, intersection, and subtraction.并且我必须制定能够给出并、交和减法的方法。

I realized that to do these methods I just have to adjust the limiting boolean functions for example:我意识到要执行这些方法,我只需要调整限制布尔函数,例如:

A = Infset(lambda x: x%2==0)
B = Infset(lambda x: x%2==1)

But if I were to try or by:但是,如果我要尝试通过:

c = A|B

it just checks for the first boolean function and not the second one.它只检查第一个布尔函数而不是第二个。 Am I doing something wrong here?我在这里做错了吗? I also tried this approach:我也尝试过这种方法:

D = (lambda x: x%2==0) or (lambda x: x%2==1) #which doesn't work. Probably why my code doesn't work
E = lambda x: x%2==0 or x%2==1 #which works

How am I supposed to connect this to my code?我应该如何将它连接到我的代码? Can someone point out my mistake?有人可以指出我的错误吗?

Use another lambda for the results.对结果使用另一个 lambda。 I think you want this:我想你想要这个:

class Infset:
    def __init__(self, f):
        self.f = f
        
    def __or__(self, other):
        return Infset(lambda x: self.f(x) or other.f(x))

    def __and__(self, other):
        return Infset(lambda x: self.f(x) and other.f(x))

    def __call__(self, x):
        return self.f(x)

A = Infset(lambda x: x%2==0)
B = Infset(lambda x: x%2==1)

C = A | B

for i in range(10):
    print(f'A({i})={A(i)!s:5} B({i})={B(i)!s:5} C({i})={C(i)!s:5}')
A(0)=True  B(0)=False C(0)=True 
A(1)=False B(1)=True  C(1)=True 
A(2)=True  B(2)=False C(2)=True 
A(3)=False B(3)=True  C(3)=True 
A(4)=True  B(4)=False C(4)=True 
A(5)=False B(5)=True  C(5)=True 
A(6)=True  B(6)=False C(6)=True 
A(7)=False B(7)=True  C(7)=True 
A(8)=True  B(8)=False C(8)=True 
A(9)=False B(9)=True  C(9)=True 

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

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