0

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?

Vermillion
  • 1,238
  • 1
  • 14
  • 29
  • Possible duplicate of [Exit while loop in Python](http://stackoverflow.com/questions/16656313/exit-while-loop-in-python) – A.Kot Oct 20 '16 at 20:59
  • http://stackoverflow.com/questions/16656313/exit-while-loop-in-python – A.Kot Oct 20 '16 at 20:59
  • I'm not sure how to interpret the answers of " Exit while loop in Python ", they don't seem to be talking about a changing list – Vermillion Oct 20 '16 at 21:05
  • 1
    Can't you use a boolean flag `has_changed = True` and your while loop is something like `while not has_changed`. Anyway, is there a reason you want to implement your own k-means? – juanpa.arrivillaga Oct 20 '16 at 21:15
  • Show the loop. And show how the list is related to the loop. – zvone Oct 20 '16 at 22:26

1 Answers1

1

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