2

I have a list of all possible substrings from a given string, I need to print just the substrings that are in alphabetical order.

s = 'abcabcd'

a = len(s)

for x in range(a):
    for y in range(x,a-1):
        print(s[x:y+2])

if I change to:

for x in range(a):
    for y in range(x,a-1):
        if s[y+1] >= s[y]:
            print(s[x:y+2])

I get the exact same answer, nothing is filtered out.

Current result is the following:

ab abc abca abcab abcabc abcabcd bc bca bcab bcabc bcabcd ca cab cabc cabcd ab abc abcd bc bcd cd

I'm looking for the result to be:

ab abc bc ab abc abcd bc bcd cd

Just substrings that are in alphabetical order.

lsu0358
  • 23
  • 4

2 Answers2

1

One possibility is to generate all substrings and check if each substring is in the lowercase alphabet:

import string

sequence = string.ascii_lowercase

# https://stackoverflow.com/questions/22469997/how-to-get-all-the-contiguous-substrings-of-a-string-in-python
all_substrings = [s[i:j+1] for i in xrange(a) for j in xrange(i,a)]

for substr in all_substrings:
    if substr in sequence and len(substr) > 1:
        print(substr)

output:

ab
abc
bc
ab
abc
abcd
bc
bcd
cd
  • This will only find substrings that are consecutive letters. If the input is `adea` it should print `ad`. – Barmar Jan 26 '19 at 01:13
  • thanks for your feedback, I'm just basing my answer on [OP's requested output](https://stackoverflow.com/questions/54374595/program-gives-list-of-all-potential-substings-from-a-given-string-need-to-filte/54374747?noredirect=1#comment95563766_54374595) – chickity china chinese chicken Jan 26 '19 at 01:21
  • All the letters that are in order in his example happen also to be consecutive. – Barmar Jan 26 '19 at 01:24
0

You're printing the substring whenever you find a pair of characters that are in order, not testing all characters in the substring.

You can use the all() function to test whether the whole substring meets the requirement.

s = 'abcabcd'
a = len(s)
for x in range(a):
    for y in range(x+2, a+1):
        if all(s[z] < s[z+1] for z in range(x, y-1)):
            print(s[x:y])
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Code in comments is impossible to read, and doesn't even work for Python because it's missing indentation. – Barmar Jan 26 '19 at 01:58
  • It looks like it's the same as mine, except you add and subtract from indexes in different places. – Barmar Jan 26 '19 at 02:04
  • Got it correct. Yours was right, I just had the original range still in Python. – lsu0358 Jan 26 '19 at 02:06