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?

5
  • Possible duplicate of Exit while loop in Python Commented Oct 20, 2016 at 20:59
  • stackoverflow.com/questions/16656313/exit-while-loop-in-python Commented Oct 20, 2016 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 Commented Oct 20, 2016 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? Commented Oct 20, 2016 at 21:15
  • Show the loop. And show how the list is related to the loop. Commented Oct 20, 2016 at 22:26

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.