diff options
author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2022-02-02 04:18:52 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-02-02 04:18:52 (GMT) |
commit | 06a491179f2de106d34c6b4973a32dce08fc4247 (patch) | |
tree | 9c941a3181495e2bd2edf78c16063b3053191e56 | |
parent | f77beacf015e9bf8762e9b9a9a631396b05d4d9a (diff) | |
download | cpython-06a491179f2de106d34c6b4973a32dce08fc4247.zip cpython-06a491179f2de106d34c6b4973a32dce08fc4247.tar.gz cpython-06a491179f2de106d34c6b4973a32dce08fc4247.tar.bz2 |
Add recipe for subslices (GH-31028)
-rw-r--r-- | Doc/library/itertools.rst | 9 |
1 files changed, 9 insertions, 0 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index f0d93eb..8c3b784 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -893,6 +893,12 @@ which incur interpreter overhead. yield from it return true_iterator(), remainder_iterator() + def subslices(seq): + "Return all contiguous non-empty subslices of a sequence" + # subslices('ABCD') --> A AB ABC ABCD B BC BCD C CD D + slices = starmap(slice, combinations(range(len(seq) + 1), 2)) + return map(operator.getitem, repeat(seq), slices) + def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) @@ -1188,6 +1194,9 @@ which incur interpreter overhead. >>> ''.join(remainder) 'dEfGhI' + >>> list(subslices('ABCD')) + ['A', 'AB', 'ABC', 'ABCD', 'B', 'BC', 'BCD', 'C', 'CD', 'D'] + >>> list(powerset([1,2,3])) [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] |