当前位置:   article > 正文

python字符串中字母排序,检查字符串是否在python中按字母顺序排列

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?

解决方案

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/651201
推荐阅读
相关标签
  

闽ICP备14008679号