Hemesh Patel Hemesh Patel - 2 years ago 386
Python Question

I want to check if a string is abecedarian

I want to check if a string is abecedarian (in alphabetical order).

def is_abecdarian(s):
index = 0
while index < len(s)-1:
if s[index + 1] > s[index]:
return True
index += 1
return False

If I switch my False and True around and switch the greater than to less than it works. What I do not understand is 'a' is not greater than 'b', yet when I run the above code it returns True.

Answer Source

The way your loop is written, it will return True if any pair of characters is ordered. It only returns False if all pairs fail. The first pair ba fails the if check, but the second pair ab passes and the function returns True.

This isn't right, because if you think about it, you can't know that a string is abecedarian until you've examined all of the characters. You should only be returning True when you're done with the loop. Conversely, as soon as you find a pair of characters that's out of order, it is safe to return False.

That's why flipping the booleans and the < operation works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download