Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if a string is in alphabetical order in python

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?

like image 859
Pav Ametvic Avatar asked Dec 01 '12 16:12

Pav Ametvic


2 Answers

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".

like image 197
JoshOrndorff Avatar answered Oct 15 '22 11:10

JoshOrndorff


This is the easiest:

def alphabetical(word):
    return list(word) == sorted(word)
like image 45
alex Avatar answered Oct 15 '22 09:10

alex