I was wondering about my apparently code for an MIT online edx class practice problem vs the provided answer code.
The assignment in question from the class was as follows:
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
Longest substring in alphabetical order is: beggh
Our automating testing will provide a value of s for you
My successful code:
curSlice='z'
for b in range(len(s)):
for e in range(b+1,len(s)):
if s[e-1]<=s[e]:
if len(s[b:e+1])>len(aas):
aas=s[b:e+1]
else:
break
print('Longest substring in alphabetical order is: '+str(aas))
The logic is to increment a beginning string letter and test every subsequent letter for increasing value then store the slice if bigger than the current slice, until the test fails and and the beginning letter increments one. At which point the process starts over.
MIT's Code:
curString = s[0]
longest = s[0]
for i in range(1, len(s)):
if s[i] >= curString[-1]:
curString += s[i]
if len(curString) > len(longest):
longest = curString
else:
curString = s[i]
print 'Longest substring in alphabetical order is:', longest
which code is more efficient? They both are about the same length, but mine has two loops. Does that make it not as optimized? Thanks