检查字符串是否在python中按字母顺序排列 [英] checking if a string is in alphabetical order in python

查看:621
本文介绍了检查字符串是否在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?

推荐答案

这具有O(n)的优势(将字符串排序为O(n log n)).如果Python中的一个字符(或字符串)以字母顺序出现在另一个字符之前,则它小于"另一个字符,因此,为了查看字符串是否以字母顺序排列,我们只需要比较每对相邻的字符即可.另外,请注意,您使用range(len(word)-1)而不是range(len(word)),因为否则,在循环的最后一次迭代中,您将越过字符串的边界.

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

这篇关于检查字符串是否在python中按字母顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆