The easiest way to see your problem is to step through the code. You can do this with the builtin debugger that comes with Python (or the nice graphical one that comes with your IDE, if you use one), or just by adding a mess of print
statements. But for something as small as this problem, you can use an online visualizer, like this one.
At first, everything seems to go well. It sees that vw
is longer than v
and remembers that. It sees that j >= w
is false so it starts over with j
.
But then, at step 16, you've got longest = 'vw'
, current = 'jx'
, and len(current) > len(longest)
is false, so you hit the else
and set current = 'x'
. And then, at step 21, with current = 'xx'
, you again hit the else and set current = 'x'
. And that's where it's going wrong.
Obviously, what you want to do here is not set current = c
every time current
is shorter than longest
, but only when c >= current[-1]
is false. Which is really just a matter of trivially rearranging your if/if/else logic. (The smallest change is to indent the second if
, but I think it may make more sense to move the else
up to where it's supposed to be, like this.)
While we're at it, you should try to come up with examples that could break your code, and then running them all through the visualizer/debugger/print-fiesta. Building a suite of unit tests to run is worth doing, even if you haven't yet gotten to the point where you know how to wrap your code in functions and use a unit test framework.