Reputation: 1308
In Python, is there a good way to end a while loop when a list does not change?
I am trying to implement the k means algorithm, which involves finding the centroids of groups of data points. Once the centroid positions no longer change, the loop is terminated.
I know that I could save the list of centroids at the beginning of the loop, and then make the while loop continue until the previous centroids match the current. But is there a more pythonic way of doing this?
Upvotes: 0
Views: 175
Reputation:
This solution is not optimal in terms of space complexity, since two copies of the list are being kept. But this allows to check whether the list has been changed or not.
from copy import deepcopy
class CList(list):
def __init__(self, *args, **kwargs):
super(CList, self).__init__(*args, **kwargs)
self.reset_state()
def reset_state(self):
self_copy = deepcopy(self)
self.last_state = self_copy
@property
def has_changed(self):
return self.last_state != self
>>> l = CList([1, 2, 3])
>>> l.has_changed
False
>>> l.append(4)
>>> l
[1, 2, 3, 4]
>>> l.has_changed
True
>>> l.reset_state()
>>> l.has_changed
False
Upvotes: 1