如何使用递归在列表中查找可除数?

时间:2018-11-19 01:22:37

标签: python list recursion

我正在制作一个函数,该函数将整数列表作为参数,并且我想查看列表中是否有5个可被2整除的项目。

例如,如果我通过以下调用调用函数“ find_numbers”:

  print(find_numbers([1,4,6,8,5,66,22,3]))

它应该返回:

   True

因为列表中有5个项目可被2(4、6、8、66和22)整除,否则应返回 false

我该怎么做?

感谢您的帮助!

注意:我需要在程序的后面使用递归,我知道使用循环会更容易,但是以后对我来说更是令人头疼的(再次,非常感谢。 )。

2 个答案:

答案 0 :(得分:1)

编辑:为误读表示歉意。现在,即使我在弄清楚您为什么需要它时也遇到了麻烦。

您遍历列表,直到找到n处的modulo 2 == 0个数字。 %是python modulo运算符。

def find_numbers(l, i=0, count=0):
  try:
    if count == 5:
      return True
    elif l[i] % 2 == 0:
      return find_numbers(l, i=i+1, count=count+1)
    else: 
      return find_numbers(l, i=i+1, count=count)
  except IndexError as e:
    return False
print(find_numbers([1, 2, 4, 6, 3, 1])) # False
print(find_numbers([1, 1, 1, 1, 1, 1])) # False
print(find_numbers([1, 2, 2, 4, 6, 1])) # False
print(find_numbers([1, 2, 2, 2, 2, 2])) # True
print(find_numbers([1])) # False

仅当x满足条件多次时,此方法将返回True。如果迭代到无法操作的值所在的列表中的索引(例如str),则会引发错误。它将捕获IndexError,以便可以像上一个示例中那样列出简短列表。


说明:这里要记住的重要一点是,最后一种情况会扩大调用堆栈。因此,如果最后一次调用返回True | False,而在此之前的每个后续调用只能返回错误(我提到的str输入用例)或True | False | Another recursive call,那么我们可以预期最后一种情况是其中之一。

与此有关的另一件好事是,它会在找到第五个匹配项时停止,因此我认为您可以进一步保存对列表的迭代。也许这就是OP想要递归的原因。

答案 1 :(得分:0)

这是另一种方法,用于保留被2整除的列表元素的记录。

def divi(a, number=5, divs=[]):
    if a == []:
        return True if len(divs) == number else False
    if not a[0] % 2:
       divs.append(a[0])
    return divi(a[1:], divs)


test = [
    [1, 2, 4, 6, 3, 1],
    [1, 1, 1, 1, 1, 1],
    [1, 2, 2, 4, 6, 1],
    [1,2, 2, 2, 2, 2],
    [1]
]

for elm in test:
    divs = []
    print('{} => {} # {}'.format(elm, divi(elm, divs=divs), divs))

输出:

[1, 2, 4, 6, 3, 1] => False # [2, 4, 6]
[1, 1, 1, 1, 1, 1] => False # []
[1, 2, 2, 4, 6, 1] => False # [2, 2, 4, 6]
[1, 2, 2, 2, 2, 2] => True # [2, 2, 2, 2, 2]
[1] => False # []