0

e.g. find substring containing 'a', 'b', 'c' in a string 'abca', answer should be 'abc', 'abca', 'bca'

Below code is what I did, but is there better, pythonic way than doing 2 for loops?

Another e.g. for 'abcabc' count should be 10

def test(x):
    counter = 0
    for i in range(0, len(x)):
        for j in range(i, len(x)+1):
            if len((x[i:j]))>2:
                print(x[i:j])
                counter +=1

    print(counter)
test('abca')
user2661518
  • 2,677
  • 9
  • 42
  • 79

2 Answers2

0

You can condense it down with list comprehension:

s = 'abcabc'
substrings = [s[b:e] for b in range(len(s)-2) for e in range(b+3, len(s)+1)]
substrings, len(substrings)
# (['abc', 'abca', 'abcab', 'abcabc', 'bca', 'bcab', 'bcabc', 'cab', 'cabc', 'abc'], 10)
Jamie Deith
  • 706
  • 2
  • 4
0

You can use combinations from itertools:

from itertools import combinations

string = "abca"

result = [string[x:y] for x, y in combinations(range(len(string) + 1), r = 2)]
result = [item for item in result if 'a' in item and 'b' in item and 'c' in item]
Moein
  • 167
  • 3
  • 11