Finding the longest alphabetical substring in a longer string
<p>I need a code to find the longest alphabetical substring in a string (s).
This is the code I'm using:</p>

<pre><code>letter = s[0]      
best = ''          
for n in range(1, len(s)):    
    if len(letter) &gt; len(best):
        best = letter
    if s[n] &gt;= s[n-1]:
        letter += s[n]    
    else:                      
        letter = s[n]
</code></pre>

<p>It works most of the time, but occasionally it gives the wrong answers and I am confused why it only works sometimes. for example when:</p>

<blockquote>
  <p>s='maezsibmhzxhpprvx'</p>
</blockquote>

<p>It said the answer was "hpprv" while it should have been "hpprvx".</p>

<p>In another case, when </p>

<blockquote>
  <p>s='ysdxvkctcpxidnvaepz'</p>
</blockquote>

<p>It gave the answer "cpx", when it should have been "aepz".</p>

<p>What's happening here?</p>

<p>The logic is almost okay except that if <code>letter</code> grows on the last loop iteration (when <code>n == len(s) - 1</code>), <code>best</code> is not changed that last time. You may insert another <code>best = letter</code> part after the loop, or re-think carefully the program structure so you won't repeat yourself.</p>

python string alphabetical