The goal of the code is to find the longest alphabetical substring within a string.
s = 'xyzbcdezzz'
longest_string = ''
current_string = ''
stringcount = 0
for n in range (len(s) - 1):
if s[n] <= s[n+1]:
current_string += (s[n]+s[n+1])
stringcount += 1
print('current string:', stringcount, current_string)
elif s[n] > s[n+1]:
if len(current_string) > len(longest_string) :
longest_string = current_string
current_string = ''
stringcount = 0
print('the longest string checked is:', longest_string, ', count reset')
if len(current_string) == len(longest_string):
print (current_string, longest_string)
if len(current_string) > len(longest_string):
print (current_string)
if len(longest_string) > len(current_string):
print(longest_string)
When I run this code, it gives 'abbccd' as the longest substring, when it's actually 'abcd'. This is because it checks the character a, comparing it to the next in the sequence, and then adds a to b giving "ab". Then it checks b, comparing to c and adds bc together, and then adds "bc" to "ab".
To fix this, I've been attempting to make the loop skip the next character if it's in alphabetical order already, and check the next one by increasing the value of 'n' once the condition is met, but this doesn't seem to do anything at all.
Advice, tips, corrections and harsh criticism are all welcomed.
EDIT: It appears I've misled some of you, so I apologise. What I meant was that if I have a string, it extracts the longest possible substring in alphabetical order. In the case of xyzbcdezzz, it will extract 'bcdezzz' because that's the longest possible alphabetical order substring, not bcde. The problem with my current code, is that it gives bccddeezzzzz. If I could skip one loop when the first if condition is true, then I think it might work in my code.