检查是否使用python中的递归进行排序

tho*_*ium 2 python sorting recursion

我试图检查列表是否使用python中的递归进行排序.如果已排序则返回true,否则返回False.

def isSorted(L):
    if len(L) < 2:
       return True
Run Code Online (Sandbox Code Playgroud)

现在,我不确定接下来应该做什么.请帮忙!

fal*_*tru 6

检查前两项.

如果订购它们,请使用递归检查下一个项目:

def isSorted(L):
    if len(L) < 2:
        return True
    return L[0] <= L[1] and isSorted(L[1:])
Run Code Online (Sandbox Code Playgroud)

旁注这个函数可以表达为单个表达式,如下所述:

return len(L) < 2 or (L[0] <= L[1] and isSorted(L[1:]))
Run Code Online (Sandbox Code Playgroud)

  • `return len(L)<2或(L [0] <= L [1]和isSorted(L [1:]))`? (2认同)