Python 递归确定序列是否为非减量序列

Python 递归确定序列是否为非减量序列,python,python-3.x,recursion,Python,Python 3.x,Recursion,我想在这里使用递归,但我的代码并不完全正确。这对于某些测试用例是正确的。在我错的地方帮助我。我必须返回递归语句。基本上,我不想扩展我的代码 def nondecreasing(l): if l==[] or len(l) == 1: return(True) else: return(nondecreasing(l[1:-1]) if (l[1]<=l[2]) else False) 也许应该是这样 def nondecreasing(l): if len(l

我想在这里使用递归,但我的代码并不完全正确。这对于某些测试用例是正确的。在我错的地方帮助我。我必须返回递归语句。基本上,我不想扩展我的代码

def nondecreasing(l):
  if l==[] or len(l) == 1:
    return(True)
  else:
    return(nondecreasing(l[1:-1]) if (l[1]<=l[2]) else False)
也许应该是这样

def nondecreasing(l):
  if len(l) <= 1:
    return True
  else:
    # the l[1] <= l[2] should be l[0] <= l[1], and l[1:-1] should be l[1:]
    return nondecreasing(l[1:]) if (l[0] <= l[1]) else False
def不减量(l):

如果len(l)你做错了两件事:

  • 您似乎认为Python索引是基于1的。不是,您正在忽略
    l[0]
    的值。这也会导致尝试访问
    l[2]
    时出现问题;当列表仅包含2个元素时,该索引不存在

    >>> def nondecreasing(l):
    ...   if l==[] or len(l) == 1:
    ...     return(True)
    ...   else:
    ...     return(nondecreasing(l[1:-1]) if (l[1]<=l[2]) else False)
    ...
    >>> nondecreasing([1, 2])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 5, in nondecreasing
    IndexError: list index out of range
    
以下代码更正了这两个错误:

def nondecreasing(l):
    if len(l) < 2:
        return True
    return nondecreasing(l[1:]) if l[0] <= l[1] else False
演示:

>>def不减量(l):
...     如果len(l)<2:
...         返回真值
...     如果l[0]>l[1]:
...         返回错误
...     返回不减损(l[1:]
...
>>>不减损([]))
符合事实的
>>>不减损([7])
符合事实的
>>>不减损([8,8,11])
符合事实的
>>>不减损([3,19,44,44,63,89])
符合事实的
>>>不减损([3,18,4])
错误的
>>>不减损([23,14,3,14,3,23])
错误的

代码应该做什么?哪些测试用例失败?此代码应检查列表是否为非递减。如果每个元素至少与前一个元素一样大,则列表是非递减的。例如[]、[7]、[8,8,11]和[3,19,44,44,63,89]是非递减的,而[3,18,4]和[23,14,3,14,3,23]不是递减的。我已经移动了您对该问题的评论,以后请您的问题添加类似的澄清。然而,你仍然没有一个明确的目标;请添加一个测试用例,以显示出现了什么问题以及您期望的输出。包括错误的完整回溯。
>>> nondecreasing([1, 2, 3, 4, 0])
True
def nondecreasing(l):
    if len(l) < 2:
        return True
    return nondecreasing(l[1:]) if l[0] <= l[1] else False
def nondecreasing(l):
    if len(l) < 2:
        return True
    if l[0] > l[1]:
        return False
    return nondecreasing(l[1:])
>>> def nondecreasing(l):
...     if len(l) < 2:
...         return True
...     if l[0] > l[1]:
...         return False
...     return nondecreasing(l[1:])
...
>>> nondecreasing([])
True
>>> nondecreasing([7])
True
>>> nondecreasing([8, 8, 11])
True
>>> nondecreasing([3, 19, 44, 44, 63, 89])
True
>>> nondecreasing([3, 18, 4])
False
>>> nondecreasing([23, 14, 3, 14, 3, 23])
False