13

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?

1
  • Pav Ametvic Do you consider 'abc def' and 'abc!=ghu' alphabetically ordered or not ? Commented Dec 1, 2012 at 18:09

7 Answers 7

21

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
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

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: 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...
i like this then: list(word) == sorted(word)
8

This is the easiest:

def alphabetical(word):
    return list(word) == sorted(word)

Comments

4

Try this, as a one-liner:

all(x <= y for x, y in zip(word, word[1:]))

Comments

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)))

2 Comments

What about apostrophes, e.g. in don't?
@DSM. Actually that was not handling properly. Removed. I think for that, we need to write a for loop.
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".

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.