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.
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])