My first solution was this but it didn't work the way I exptected to. By this I mean that I wanted to add some item to this set and the set would be still able to iterate through the remained items and also the new item/s. For example if I have into e_closure_statesFinal the nums {2,3} and after the if statement the number 5 will be added I would want the first for loop to iterate through {2,3} and 5 also. Thanks in advance and sorry if I am not comprehensible.
for nextstate in e_closure_statesFinal:
print(nextstate)
for y in range(state,len(self.states)+ 1):
if ((nextstate, '@') in self.transition_function.keys()):
e_closure_statesFinal = e_closure_statesFinal|self.transition_function[(nextstate, '@')]
else :
break
Second solution that worked but i want to know if there is a faster way.
i = 0
while i < len(e_closure_statesFinal):
for nextstate in e_closure_statesFinal:
for y in range(state,len(self.states)+ 1):
if ((nextstate, '@') in self.transition_function.keys()):
e_closure_statesFinal = e_closure_statesFinal |self.transition_function[(nextstate, '@')]
else :
break
i += 1
What you're specifically asking for cannot be done; modifying a set
while iterating it is forbidden (even if it worked, the nature of Python's set
is such that new elements could come before or after the ones already iterated, so it wouldn't be consistent, which is part of why this is forbidden). You could conceivably run a nested loop that ran over a copy of the original set
, then ran over the difference between the resulting set
and the original, etc. Something like:
workingset = {...}
lastset = set()
while lastset != workingset: # Until a run doesn't change workingset
newelems = workingset - lastset
lastset = workingset.copy()
for elem in newelems: # Run over all new elements in workingset
... do stuff ...
if somecondition:
workingset.add(someelem) # Maybe add stuff to workingset