递归确定序列是否不减少

时间:2017-03-19 09:07:14

标签: 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)

此代码应检查列表是否不减少。如果每个元素至少与前一个元素一样大,则列表是非递减的。例如,[][7][8,8,11][3,19,44,44,63,89]不会减少,而[3,18,4][23,14,3,14,3,23]则不会减少。

更长的非减少测试用例失败:

>>> nondecreasing([3,19,44,44,63,89])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in nondecreasing
  File "<stdin>", line 5, in nondecreasing
  File "<stdin>", line 5, in nondecreasing
IndexError: list index out of range

2 个答案:

答案 0 :(得分:1)

You are doing two things wrong:

  • You seem to assume Python indexing is 1-based. It's not, you are ignoring the value of l[0]. This also causes an issue with trying to access l[2]; that index doesn't exist when your list only contains 2 elements.

    >>> 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
    
  • You are ignoring the last value of the list when recursing; slicing to [...:-1] removes the last element, causing you to fail to detect a single last decreasing value:

    >>> nondecreasing([1, 2, 3, 4, 0])
    True
    

The following code corrects both errors:

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

The l[1:] slice copies all elements except the first one.

Personally, I'd probably not use the conditional expression on the last line. The following is a little clearer:

def nondecreasing(l):
    if len(l) < 2:
        return True
    if l[0] > l[1]:
        return False
    return nondecreasing(l[1:])

Demo:

>>> 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

答案 1 :(得分:0)

也许它应该是

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