2

So far i've got :

s = 'azcbobobegghakl'
i = 0
j = 1 

temp = ''  #temporary variable I use to change longest
longest = ''   
for b in range(len(s)):
    if s[i] <= s[j]: #checks if it's in alphabetical order
        temp+=s[i] 
        if len(longest) < len(temp):
           longest  = temp       
    else: 
        temp = ''    #reset temp after every substring  
    if len(longest) < len(temp):
        longest  += temp      #update longest if the new substring is longer
    i +=1
    if j < len(s) - 1 : # because otherwise i get an IndexError
       j +=1


print('Longest substring in alphabetical order is:', longest)

Now my problem is that I always get the correct string BUT without the last letter . (for example here instead of "beggh" i get "begg").

I also have to make it so that if it's a tie, the first one counts as the longest (if s = abcbcd, abc should be the longest )

And lastly I know this question has been asked several times here already but i want to fix the code I came up with if possible, not just use someone else's code entirely.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
Skygear
  • 90
  • 6
  • 3
    My head is going to blow if I keep thinking on your code. There are too many things that does not make sense in my way of thinking. Just take a couple of general hints: Don't use `i` and `j`, use `i` and `i+1`. To avoid the IndexError at the end, don't iterate over `range(len(s))`, iterate over `range(len(s)-1)`. Finally, don't iterate over `b`. `b` is not used for anything else. Iterate over `i`. This changes will clean up quite a lot of things and difficulties. – Poshi Jul 06 '18 at 21:31
  • 1
    @ti7 How on earth would `findall` find an alphabetically ordered string? – DYZ Jul 06 '18 at 21:35
  • @Poshi Thanks for the suggestions. Hopefully it's a bit better understandability wise now . – Skygear Jul 06 '18 at 21:42
  • Better. But you don't have to initialize `i`, it is being overwritten in the `for` loop. The same for the increment, it will be overwritten by the next iteration on the `for` loop. – Poshi Jul 06 '18 at 21:45
  • @NikolaiTh3KillerKirilov Please do not update your question based on given answers. Otherwise, those answers make no sense to future users. – Olivier Melançon Jul 06 '18 at 22:05
  • @DyZ trivializing difficult a CS problem due to illness and poor description – ti7 Jul 08 '18 at 06:47

5 Answers5

2

You are comparing s[i] with s[i+1], but only adding s[i] to temp. Instead always start with the current letter in temp and add s[i+1] to temp after comparison

s = 'azcbobobegghakl'
i = 0

temp = s[0]   #temporary variable I use to change longest
longest = ''   
for i in range(len(s)-1):
    if s[i] <= s[i+1]:  #checks if it's in alphabetical order
        temp+=s[i+1]
        if len(longest) < len(temp):
           longest  = temp       
    else: 
        temp = s[i+1]     #reset temp after every substring
    if len(longest) < len(temp):
        longest  += temp    #update longest if the new substring is longer
    i +=1



print('Longest substring in alphabetical order is:', longest)

# Longest substring in alphabetical order is: beggh
Sunitha
  • 11,777
  • 2
  • 20
  • 23
1

You aren't taking the current character into account if you find the next character isn't in alphabetical order, and that's why you're missing one character in the end.

Instead, you should always process the current character first before resetting temp if the next character isn't in order.

s = 'azcbobobegghakl'
i = 0

temp = ''   #temporary variable I use to change longest
longest = ''   
for i in range(len(s)-1):
    temp += s[i]
    if len(longest) < len(temp):
        longest = temp
    if s[i] > s[i+1]:  #checks if it's in alphabetical order
        temp = ''     #reset temp after every substring
    if len(longest) < len(temp):
        longest  += temp    #update longest if the new substring is longer  
    i +=1



print('Longest substring in alphabetical order is:', longest)

This outputs:

Longest substring in alphabetical order is: beggh
blhsing
  • 91,368
  • 6
  • 71
  • 106
0
s = 'azcbobobegghakl'
i = 0
j = 1 

temp = ''  #temporary variable I use to change longest
longest = '' 


for b in range(0, len(s) -1):
    if s[b] <= s[b + 1]: #checks if it's in alphabetical order
        if len(temp) == 0:
            temp+= s[b]
            temp+= s[b+1]
        else:
            temp+= s[b+1]

        if len(longest) < len(temp):
           longest  = temp       
    else: 
        temp = ''    #reset temp after every substring  
    if len(longest) < len(temp):
        longest  += temp      #update longest if the new substring is longer
    i +=1
    if j < len(s) - 1 : # because otherwise i get an IndexError
       j +=1


print('Longest substring in alphabetical order is:', longest)
blhsing
  • 91,368
  • 6
  • 71
  • 106
ergesto
  • 367
  • 1
  • 8
0

Though I have mentioned how to fix your code in my other answer, I also wanted to say that the straight forward way of doing it is to use itertools.accumulate

list(accumulate(s, lambda s, c: s+c if s[-1]<=c else c) )
# ['a', 'az', 'c', 'b', 'bo', 'b', 'bo', 'b', 'be', 'beg', 'begg', 'beggh', 'a', 'ak', 'akl']

So a one-liner to find the longest substring in alphabetical order is

sorted(accumulate(s, lambda s, c: s+c if s[-1]<=c else c), key=len)[-1]
# 'beggh'
Sunitha
  • 11,777
  • 2
  • 20
  • 23
0

To solve the problem at then end you need to put it some kind of break when the code reaches the final index. Additionally, you need to add a bit of code for the loop to reset if you reach the end of the string and it's still in alphabetical order (see below). Lastly, for the situation in which the longest string is only one character, you need to define your starting variables for longest_word and word at s[0}. Just keep at it and you'll get it eventually. pythontutor.com is a great tool for debugging and troubleshooting.

s = 'abcdefghijklmnopqrstuvwxyz'
a = 0
b = 1
longest_word = s[0]
word = s[0]
for i in range(len(s)):
    a = 0
    b = 1
    if i == len(s) - 2 or b > len(s)-1:
        i += 1
        print('Longest substring in alphabetical order is:', longest_word)
        break
    while (b < len(s)-i) and (s[i+a] <= s[i+b]):
        word = s[i:i+b+1]
        a += 1
        b += 1
    if len(word) > len(longest_word):
        longest_word = s[i:i+b]
    else: 
        i += 1