我必须创建一个函数,如果列表已排序,则该函数返回True或False

时间:2020-02-12 01:13:24

标签: python python-3.x

我必须创建一个名为isSorted()的函数,并测试在Python 3.7中列表是否已排序。无论发生什么情况,该函数都必须返回TrueFalse

这是我的代码

def isSorted(newList):
    for x in newList:
        if newList[0] <= x:
            return True
        else:
            return False 

def main ():
    newList = [1, 2, 3]
    print(isSorted(newList))
    newList = [1]
    print(isSorted(newList))
    newList = list(range(10))
    print(isSorted(newList))
    newList[9] = 3
    print(isSorted(newList))

if __name__ == '__main__':
    main()

我特别需要newList[9] = 3行来返回False,但它总是返回True。谁能解释为什么?

1 个答案:

答案 0 :(得分:2)

两个问题:

(1)您应该将每个元素与上一个元素进行比较,而不是与第一个元素进行比较。

(2)如果第一次检查在循环中成功,则立即返回True。您的代码甚至不处理第9个元素。

固定的实现可能是:

def isSorted(newList):
    for i in range(len(newList) - 1):
        if newList[i] > newList[i + 1]:
            return False
    return True

然后您的测试应打印:

True
True
True
False