Last active
August 29, 2015 14:09
-
-
Save rob-smallshire/9e5129b8b35facee2fbe to your computer and use it in GitHub Desktop.
This is the only quasi-legitmiate use I have found for the while..else construct in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def pop_count_until(stack, predicate): | |
"""Count the number of items which need to be popped off a stack | |
for the top item to satisfy a predicate. | |
The stack argument is modified by this call. If the return value is | |
non-negative the top item on the stack will satisfy the predicate | |
on return. | |
Args: | |
stack: Any object supporting: | |
item = stack.pop() # Remove and return the top item | |
stack.append(item) # Push an item to the top | |
if stack: # False in a boolean context when empty | |
predicate: A predicate used for testing items to be popped off the stack. | |
Returns: | |
The number of items which were popped off the stack before the | |
top item satisfied the predicate, if such an item was present in the | |
stack, otherwise -1. | |
""" | |
count = 0 | |
while stack: | |
item = stack.pop() | |
if predicate(item): | |
stack.append(item) | |
break | |
count += 1 | |
else: | |
count = -1 | |
return count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment