sis a string of lower case characters.
Write a program that prints the longest substring of
sin which the letters occur in alphabetical order. For example, if
s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if
s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
I have been working on a edX course, MITx: 6.00.1x Introduction to Computer Science and Programming Using Python. Encountering the problem mentioned above, I set out to write a piece of code which I found to be the most disgusting to date(excluding Project Euler draft code).
s can be any input, but in my case, edX will automatically input a value for
s, so I do not need to define
first=0 second=1 strang1='' strang2='' while second<len(s): if second>=len(s): break elif s[first]<=s[second]: strang1+=s[first:second+1] while second<=len(s): second+=1 if second>=len(s): break elif s[second]>=strang1[-1]: strang1+=s[second] if len(strang1)>len(strang2): strang2=strang1 else: if len(strang1)>len(strang2): strang2=strang1 strang1='' first=second-1 break else: if len(s[first])>len(strang2): strang2=s[first] first+=1 second+=1 print("Longest substring in alphabetical order is:" + strang2)
The code can accurately take on any input(if defined) and output it accurately(according to the edX's test runs). I'm looking to make my code more efficient, any suggestions? I'll accept any, fancy newfangled functions or maybe a total rework, I don't mind.