Letters have an order
Letters line up in the order of the alphabet, as in a dictionary. So you can ask which of two letters comes first. The letter b comes after a, and c comes after b. You can compare letters with less than and greater than, just like numbers.
A word is in alphabetical order when no letter comes before the one in front of it. "abbey" is in order, but "abca" is not, because the last a comes before the c.
"a" < "b" # True "c" < "b" # False
Check each pair of neighbours
To check a whole word, look at each letter and the one just before it. Start from the second letter, because the first has nobody in front of it. If a letter comes before its neighbour, the word is out of order, and you can say no right away.
If you get to the end without finding a problem, the answer is yes. A word of one letter, or no letters, is in order, because there is nothing to compare.
for i in range(1, len(s)):
if s[i] < s[i - 1]:
return False
return True- now
- b
- before
- a
Compare b with the letter before it, a. b doesn't come before a, so that's fine.