今天是个好日子。我的作业需要一点帮助——请不要给我答案;只是帮我把这个概念化。
我需要创建一个像数学集一样的类函数。这意味着它可以是一个无限集。类函数将一个 bool 函数作为参数,并将创建一个包含所有符合 bool 函数的自然数(包括 0)的集合
class Infset:
def __init__(self, f):
self.inf = set()
self.x = 0
while True:
if f(self.x) == True:
self.inf.add(self.x)
self.x += 1
else:
self.x += 1
到目前为止,我创建了一个真正生成无限集的类,当然它会返回 MemoryError。bool 函数将作为 lambda 函数给出,例如:
lambda x: x%3==2
lambda x: x*x>5
我还必须制作运算符方法,例如:def __or__(self, other):
return #Union of two sets
def __and__(self, other):
return #intersection of two sets
def __sub__(self, other):
return #difference of two sets
它还返回一个“无限循环”也许我可以将类 Infset 视为限制 bool 函数?我希望任何人都可以让我对此有所了解。
编辑!*
在浏览了评论后,它帮助我更好地概念化了这一点。我将 bool 函数作为对象,并将其视为数字的模型
class Infset:
def __init__(self, f):
self.f = f
def __or__(self, other):
return Infset(self.f or other.f)
自为或 方法(联合)我需要找到适合第一个 bool 函数或第二个 bool 函数的数字。编辑**
def __or__(self, other):
return Infset(self.f or other.f)
当我用两个 lambda 函数尝试这个时,它不起作用a = Infset(lambda x: x%2==0)
b = Infset(lambda x: x%2 == 1)
c = a | b # should look like Infset(lambda x: x%2==0 or lambda x: x%2 == 1)
它只检查第一个条件而忽略第二个条件。我在这里做错了什么?
最佳答案
您需要存储函数 f
,而不是存储数字。本身。做工会等需要新建f
基于 self.f
和 other.f
这给出了是否给定 x
的正确答案是在工会。
关于python - 关于python中一个 "infinite"集合类的问题(作业),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64869466/