Skip to content

Instantly share code, notes, and snippets.

@tai2
Created July 25, 2011 15:45
Show Gist options
  • Save tai2/1104424 to your computer and use it in GitHub Desktop.
Save tai2/1104424 to your computer and use it in GitHub Desktop.
enumerate all subsequences in a sequence
# enumerate all subsequences in a sequence
def subsequences(s):
for i in range(len(s)):
for j in range(len(s) - i):
yield s[j:j + i + 1]
if __name__ == '__main__':
assert list(subsequences([])) == []
assert list(subsequences([1])) == [[1]]
assert list(subsequences([1, 2])) == [[1], [2], [1,2]]
assert list(subsequences([1, 2, 3])) == [[1], [2], [3], [1,2], [2,3], [1,2,3]]
assert list(subsequences((1, 2, 3))) == [(1,), (2,), (3,), (1,2), (2,3), (1,2,3)]
assert list(subsequences('abc')) == ['a', 'b', 'c', 'ab', 'bc', 'abc']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment