12

I've put together the following code to check if a string/word is alphabetically ordered:

def isInAlphabeticalOrder(word):
    word1=sorted(word)
    word2=[]
    for i in word:
        word2.append(i)
    if word2 == word1:
        return True
    else:
        return False

but I feel like there must be a more efficient way (fewer lines of code) to check other than turning the strings into lists. Isn't there a operand to sort strings alphabetically without turning each char into a list? Can anyone suggest a more efficient way?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Pav Ametvic
  • 1,727
  • 4
  • 12
  • 14
  • Pav Ametvic Do you consider **'abc def'** and **'abc!=ghu'** alphabetically ordered or not ? – eyquem Dec 01 '12 at 18:09

7 Answers7

19

This has the advantage of being O(n) (sorting a string is O(n log n)). A character (or string) in Python is "less than" another character if it comes before it in alphabetical order, so in order to see if a string is in alphabetical order we just need to compare each pair of adjacent characters. Also, note that you take range(len(word) - 1) instead of range(len(word)) because otherwise you will overstep the bounds of the string on the last iteration of the loop.

def isInAlphabeticalOrder(word):
    for i in range(len(word) - 1):
        if word[i] > word[i + 1]:
            return False
    return True
i love stackoverflow
  • 1,555
  • 3
  • 12
  • 24
15

This is a simple (and Python idiomatic) way to do this:

def isInAlphabeticalOrder(word):
    return word==''.join(sorted(word))

>>> isInAlphabeticalOrder('abc')
True
>>> isInAlphabeticalOrder('acb')    
False
  • wow, that is pretty good. But, I get the feeling the OP is a programming student, being introduced to looping. If that's true, doing things this way would not be conducive to understanding loops. :) – kreativitea Dec 01 '12 at 17:06
  • @kreativitea: Maybe. But I think it also important for a student to learn the idioms of the chosen language. This is a very idiomatic way to do this in Python. If the language was C, then looping or a library is the way... –  Dec 01 '12 at 17:10
  • 6
    i like this then: `list(word) == sorted(word)` – kreativitea Dec 01 '12 at 17:13
8

This is the easiest:

def alphabetical(word):
    return list(word) == sorted(word)
alex
  • 2,381
  • 4
  • 23
  • 49
4

Try this, as a one-liner:

all(x <= y for x, y in zip(word, word[1:]))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
3

You can use generator in your function like this: -

def isInAlphabeticalOrder(word):
    return all((word[i+1] >= word[i] for i in range(len(word) - 1)))

The generator gets each value of i from the given range, and compare the character at that index with the one in the previous index. And all the comparison results are passed to all function, which will return True if all the values are True.

>>> def isInAlphabeticalOrder(word):
        return all((word[i+1] >= word[i] for i in range(len(word) - 1)))

>>> isInAlphabeticalOrder("rohit")
False
>>> isInAlphabeticalOrder("aabc")
True
>>> isInAlphabeticalOrder("abc")
True

Of course that does not consider case-insensitivity. If you want to consider it, then change the return statement to: -

return all((str.lower(word[i+1]) >= str.lower(word[i]) for i in range(len(word) - 1)))
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

Several answers have already addressed the actual string comparison. But I want to add a bit about your return logic.

It is common for beginners to write code like:

if something == somethingElse:
  return True
else:
  return False

That code can always be simplified like this:

return something == somethingElse

If that code doesn't make sense at first it reads as, "Compare something to SomethingElse, and return the result of the comparison".

JoshOrndorff
  • 1,591
  • 9
  • 19
0

The program will return true if the word is alphabetically arranged or false otherwise. The second argument wordList is initialized to None meaning the program will check for any word that you put in including numbers:

def isAlphabeticalOrder(word, wordList = None):
if (len(word) > 0):
    curr = word[0]
for letter in word:
    if (curr > letter):
        return False
    else:
        curr = letter
if wordList is None:
    return True
return word in wordList
chibole
  • 942
  • 6
  • 15