Last active
August 29, 2015 14:24
-
-
Save jfinkels/5b3cac01b7206f230ae6 to your computer and use it in GitHub Desktop.
Iterate over all suffixes of an iterable in Python.
This file contains hidden or 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
from itertools import islice | |
from itertools import tee | |
def tails(iterable): | |
iterator = iter(iterable) | |
while True: | |
tail, iterator = tee(iterator) | |
yield tail | |
# Try to pop the next element of the iterable. If there are no | |
# more elements in the iterable, there are no more suffixes so | |
# we break out of the loop. | |
try: | |
next(iterator) | |
except StopIteration: | |
break | |
def tails_recursive(iterable): | |
iterator = iter(iterable) | |
tail, iterator = tee(iterator) | |
yield tail | |
try: | |
next(iterator) | |
except StopIteration: | |
return | |
for tail in tails_recursive(iterator): | |
yield tail | |
# This only works if the iterable also has a __len__ method. | |
def tails_islice(iterable): | |
n = len(iterable) | |
for tail in (islice(iterable, i, n) for i in range(n + 1)): | |
yield tail |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment