I often find I want to repeat a block of code until some state stops changing. As an example, suppose rects
is a list of rectangles and rect
is a single rectangle and we want to keep merging rect
with rectangles from rects
, enlarging rect
each time, until there's nothing overlapping:
stable = False
while not stable:
stable = True
for rect2 in list(rects):
if rect.overlaps(rect2):
rect = rect.merge(rect2)
rects.remove(rect2)
stable = False
In Haskell, we have this natural solution https://stackoverflow.com/a/7443379/125940 . What is the most natural way to achieve this in Python? I came up with this:
class DoUntilStable:
def __init__(self):
self._stable = False
def __iter__(self):
while not self._stable:
self._stable = True
yield self
def changed(self):
self._stable = False
for dus in DoUntilStable():
for rect2 in list(rects):
if rect.overlaps(rect2):
dus.changed()
rect = rect.merge(rect2)
rects.remove(rect2)