首页 > 解决方案 > 将迭代函数转换为递归函数

问题描述

我正在尝试将此迭代函数转换为递归函数。该函数接受整数 x 和整数列表。for 循环删除列表中的一个元素

def function(x, arr):
  for v in arr:
    if v % x == 0:
      arr.remove(v)
  return arr

我试过这样做,但它似乎不起作用:

out = []
def removeMultiples(x, arr):
  if len(arr) < 1:
    return arr
  else:
    if arr[0] % x == 0:
      out.append(arr[0])
      return out + removeMultiples(x, arr[1:])
    else:
      return out + removeMultiples(x, arr[1:])

标签: pythonrecursion

解决方案


此函数的迭代版本可以使用列表推导

def function(x, arr):
    return [i for i in arr if i % x != 0]

递归版本可能看起来像这样

def removeMultiples(x, arr):
    if not arr:
        return []
    current, rest = arr[0], arr[1:]
    if current % x != 0:
        return [current] + removeMultiples(x, rest)
    else:
        return removeMultiples(x, rest)

例如

>>> values = [1,2,3,4,5,6,7,8]
>>> function(2, values)
[1, 3, 5, 7]
>>> removeMultiples(2, values)
[1, 3, 5, 7]

请注意,这两个版本都创建并返回一个新列表,而不是从现有列表中删除元素。


推荐阅读