EzrealReal
EzrealReal

Reputation: 83

Finding Longest substring in alphabetical order (Need Advice for Logic)

Hi everyone I am trying to solve one of the challenging questions to find the Longest substring in alphabetical order.

I am so close to getting the answer right, but my code does not include the last letter.

Below is my code:

s = 'azcbobobegghakl'
word = ''
longest = ''
temp = ''
for x in range(len(s)):
    if (s[x] <= s[x+1:x+2]):
        word = s[x]
        temp += word
        if len(temp) > len(longest):
            longest = temp      
    else:
        temp = ''
print('Longest substring in alphabetical order is: ' + longest)

How can I include the last letter by setting another condition? I feel my logic is correct but I have a difficult time including the last letter.

Like correct answer, beggh, I got begg and abcdc, I got ab

Upvotes: 1

Views: 134

Answers (2)

Paul Cornelius
Paul Cornelius

Reputation: 11008

Instead of adding s[x] to temp, add s[x+1].

Initialize both temp and longest to the first character, so that the code will work with a 1-character string or a string that has no sequence in alphabetical order.

Stop the iteration one character before the end so s[x+1] doesn't give you an IndexError.

When the next character is out of order, reinitialize temp to the next character.

You can eliminate the variable "word".

s = 'azcbobobegghakl'
longest = s[0]
temp = s[0]
for x in range(len(s)-1):
    if (s[x] <= s[x+1]):
        temp += s[x+1]
        if len(temp) > len(longest):
            longest = temp      
    else:
        temp = s[x+1]
print('Longest substring in alphabetical order is: ' + longest)

Upvotes: 1

revliscano
revliscano

Reputation: 2272

You were almost there, indeed. But take a look at this very similar approach:

def longest_abc(s):
    word = s[0]
    longest = word
    for i in range(1, len(s)):
        if s[i] >= s[i - 1]:
            word += s[i]
        else:
            word = s[i]
        if len(word) > len(longest):
            longest = word
    return longest

>>> longest_abc('azcbobobegghakl')
'beggh'
>>> longest_abc('abcdc')
'abcd'

Upvotes: 1

Related Questions