How can I represent an "infinite" set based off a predicate, without storing all the elements?

Question:

For homework, I was asked to write a class that acts like a mathematical – i.e., potentially infinite – set. The constructor needs to have a parameter that will be given a function that returns a boolean value (a boolean predicate). It will be given as a lambda, for example lambda x: x%3==2 or lambda x: x*x>5.

The resulting object should represent the set of all natural numbers(including 0) that satisfy the predicate.

I also need to implement __or__, __and__ and __sub__ to give the union, intersection and difference of two sets.

So far, I have this code:

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

Of course, this really does try to make an infinite set, which results in a MemoryError.

How can I represent a potentially infinite set with finite storage space?

Asked By: WinnyDaPoo

||

Answers:

Instead of storing numbers, you need to store the function f itself. To do unions and so on, you need to create a new f based on self.f and other.f which gives the right answer for whether a given x is in the union.

Answered By: kaya3
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.