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?
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".
This is the easiest:
def alphabetical(word):
return list(word) == sorted(word)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With