]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Add recipe for subslices (GH-31028)
authorRaymond Hettinger <rhettinger@users.noreply.github.com>
Wed, 2 Feb 2022 04:18:52 +0000 (22:18 -0600)
committerGitHub <noreply@github.com>
Wed, 2 Feb 2022 04:18:52 +0000 (22:18 -0600)
Doc/library/itertools.rst

index f0d93ebb6b21ae8e64ab6952015c7b00305e4185..8c3b7842f7f6a75c33db8ca6f7ddfda5a5702615 100644 (file)
@@ -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)]