I created this Level class with two objects: name & the precondition of level.
With the property function at the end, I want to get a set of all preconditions for a certain level.
(For example: for Level 3 the precondition is {Level 2}
, and for Level 2 the precondition is {Level 1}
, so the all preconditions of Level 3 is {Level 1, Level 2}
)
class Level:
def __init__(self,
name: str,
preconditions: list[Level] = [],
):
self.name = name
self.preconditions = set(preconditions)
def __repr__(self):
return f'Level(name="{self.name}", preconditions={self.preconditions})'
@property
def all_preconditions(self) -> set[Level]:
preconditions = set()
for p in self.preconditions:
preconditions.update(p.preconditions)
p = p.preconditions
return preconditions
My code works so far, but I have a loop problem. There are some Levels who are dependent on each other. For example: Level A precondition = {Level B} & Level B precondition = {Level A}.
In this case, I'm getting an infinite loop of preconditions as an output. For example:
{Level(name="A", preconditions={Level(name="B", preconditions={Level(name="A", precondition={Level(name="B", preconditions=set(...)}
Could anyone help me how I stop the loop and only get one precondition?