Home > Net >  string output all substring including non-adjacent
string output all substring including non-adjacent

Time:01-13

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

CodePudding user response:

You can use itertools.combinations.

from itertools import combinations

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

Output:

a
b
c
ab
ac
bc
abc

CodePudding user response:

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']
  • Related