-4
 s = 'abcabcabc'
 i = 0
 j = 1
 longestSubString = ''
 realString = ''
 while (j < len(s)):
    if i == 0:
        longestSubString = s[i]        
    if (s[j] >= s[i]):
        longestSubString = longestSubString + s[i] 
        if len(longestSubString) > len (realString):
            realString = longestSubString
        i += 1
        j += 1
    else:
        longestSubString = ''
        i += 1
        j += 1
print ("Longest SubString is: " + realString)   

Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print beggh

After spending hours in building the code I didn't get the desired result. Can someone please have a look at my code and guide me wherever I am wrong.

m4110c
  • 427
  • 4
  • 10
Sunny
  • 11
  • 1
  • 3
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [MCVE]. – Łukasz Rogalski Oct 23 '16 at 11:26
  • ".. your program should print" *what*? – Jongware Oct 23 '16 at 14:00

2 Answers2

1

This should do what you want. I used Python3, but it should also work with Python2

s = 'azcbobobegghakl'
res = ''
tmp = ''

for i in range(len(s)):
    tmp += s[i]
    if len(tmp) > len(res):
        res = tmp
    if i > len(s)-2:
        break
    if s[i] > s[i+1]:
        tmp = ''

print("Longest substring in alphabetical order is: {}".format(res))
m4110c
  • 427
  • 4
  • 10
0

I'd say it's something like this you are after. Instead of comparing the characters s[j] > s[i] you need to compare their indices. You can use string.ascii_lowercase.index(s[i]) for this.

Get character position in alphabet

EDIT: Refactored a bit to make it more readable

import string

s = 'azcbobobegghakl'
i = 0
currentSubString = ''
longestSubString = ''

while (i < len(s)):

    positionCurrent = string.ascii_lowercase.index(s[i])
    positionPrevious = string.ascii_lowercase.index(s[i-1])
    currentCharacter = s[i]
    i += 1

    if (positionCurrent != positionPrevious + 1):
        currentSubString = ''

    currentSubString += currentCharacter

    if len(longestSubString) < len(currentSubString):
        longestSubString = currentSubString

print("Longest SubString is: " + longestSubString)
Community
  • 1
  • 1
amstel
  • 1
  • 3