【问题标题】:Python 3 while loop not fully looping? [duplicate]Python 3 while 循环没有完全循环? [复制]
【发布时间】:2016-01-31 11:29:02
【问题描述】:

所以我已经有一段时间了。我正在尝试创建一个函数来检查列表中的数字是否在增加。例如 [1, 2, 3] 为 True,但 [1, 3, 2] 为 False。我已经到了它会说 [1, 2, 3] 是 True,[3, 2, 1] 是 False,但 [1, 3, 2] 仍然是 True 的地步。我认为这只是因为只读取前两个位置?

下面是函数供参考:

 def increasing(lst):
    index = 0
    index2 = index + 1
    while index < len(lst):
        if lst[index] >= lst[index2]:
            index += 1
            index2 += 1
            return False
        else:
            while index < len(lst):
                if lst[index] < lst[index2]:
                    index += 1
                    index2 += 1
                    return True

【问题讨论】:

  • index 有没有可能不变?
  • 注意单元素和空列表。

标签: python


【解决方案1】:

试试这个:

def increasing(lst):
    return lst == sorted(lst)

这会检查列表是否已排序。

【讨论】:

  • 这比线性遍历列表( O(n log(n)) vs O(n) )要慢,但在大多数情况下可能没问题。
【解决方案2】:

您的代码似乎过于复杂。只需使用循环检查第 i 个元素是否大于第 (i-1) 个元素即可。

编辑:这是简单的代码

def isSorted(l):
    i = 1
    while i < len(l):
        if l[i] < l[i-1]:
            return False
        i += 1
    return True
isSorted([1, 2, 3]) #True
isSorted([1, 3, 2]) #False

【讨论】:

  • 呃,当然,总会有人不屑一顾地投反对票 :(
  • 嘿,感谢您的回复,这帮助很大!
  • 虽然另一个答案中的lst == sorted(lst) 在技术上是正确的,但如果输入列表未排序,它会对其进行排序并创建一个新的排序列表。这就是在这种情况下浪费的所有工作。然而,一旦检测到一个乱序的值,这种方法就会短路。因此,虽然看起来不像 Pythonic,但我认为这里的解决方案对于大型列表来说性能更高。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 2017-07-31
  • 2022-11-18
  • 2014-11-02
  • 1970-01-01
  • 2017-04-03
相关资源
最近更新 更多