2

I have a function remove_it() that tries to remove some data and the removed data is added to the set removed. The main logic is that if there is more to remove, keep removing and my code looks like this:

    removed = set()
    prev_count = -1

    while prev_count != len(removed):
        prev_count = len(removed)
        remove_it()

It bothers me a little that the while loop condition and the next line look very similar to each other. Is it normal or is there a better way to do it?

The logic in remove_it() is quite complicated: it detects some graph structure topology and after each round of removal the topology changes and I cannot know how it changes until the removal is done.

I was thinking of return bool value from remove_it() to track whether the set removed has changed. Then the while loop would be like

while remove_it():
     pass

which is also strange to me. Is there a better way?

3
  • could you give somme examples of the data? might help to better understand the problem/come up with an optimal solution Commented Jan 26, 2017 at 18:24
  • Interesting. In C, my stronger language, this would indeed be while(function()) ; -- note the explicit semicolon. Nothing like that for Python? Commented Jan 26, 2017 at 18:24
  • 2
    The second looks quite natural. Perhaps a rename to remove() and we are done: you thus say, "while removing, keep going". Commented Jan 26, 2017 at 18:24

1 Answer 1

2

Your remove_it function has side effects and this makes program harder to read. You can rewrite it so that instead of modifying global removed variable it would return set of removed values. Then you can rewrite the loop:

removed = set()

while True:
    removed_batch = remove_it()
    if removed_batch:
        removed += removed_batch
    else:
        break
Sign up to request clarification or add additional context in comments.

1 Comment

Best advice ever, when a function act outside it's own scope, makes it return what it did or a true/false value, more idiomatic on usage and easier to maintain on long term.

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.