Skip to content

Commit 06a4911

Browse files
authored
Add recipe for subslices (GH-31028)
1 parent f77beac commit 06a4911

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

Doc/library/itertools.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -893,6 +893,12 @@ which incur interpreter overhead.
893893
yield from it
894894
return true_iterator(), remainder_iterator()
895895

896+
def subslices(seq):
897+
"Return all contiguous non-empty subslices of a sequence"
898+
# subslices('ABCD') --> A AB ABC ABCD B BC BCD C CD D
899+
slices = starmap(slice, combinations(range(len(seq) + 1), 2))
900+
return map(operator.getitem, repeat(seq), slices)
901+
896902
def powerset(iterable):
897903
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
898904
s = list(iterable)
@@ -1188,6 +1194,9 @@ which incur interpreter overhead.
11881194
>>> ''.join(remainder)
11891195
'dEfGhI'
11901196

1197+
>>> list(subslices('ABCD'))
1198+
['A', 'AB', 'ABC', 'ABCD', 'B', 'BC', 'BCD', 'C', 'CD', 'D']
1199+
11911200
>>> list(powerset([1,2,3]))
11921201
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
11931202

0 commit comments

Comments
 (0)