赞
踩
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?
解决方案
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。