string output all substring including non-adjacent

Question:

For example the string ‘abc’ outputs all substrings, which are 'a', 'b', 'c', 'ab', 'ac', 'bc','abc'
Importantly, 'ac' is a non-adjacent substring.

lines = input()
res = [lines[i: j] for i in range(len(lines)) for j in range(i + 1, len(lines) + 1)]

which outputs all adjacent substrings. How can I modify this function to include non-adjacent substring? Thank you

Asked By: ryrie23

||

Answers:

You can use itertools.combinations.

from itertools import combinations

s = 'abc'
for i in range(1, len(s)):
    for item in combinations('abc', i):
        print(''.join(item))

Output:

a
b
c
ab
ac
bc
abc
Answered By: I'mahdi

You can use combinations from itertools:

# s = 'abc'
>>> [''.join(j) for i in range(1, len(s)+1) for j in combinations(s, i)]

['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
Answered By: Corralien
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.