简体   繁体   English

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

[英]How to use recursion to find divisible numbers in list?

I'm making a function takes a list of integers as a argument, and I want to see if there is 5 items in the list that are divisible by 2. 我正在使一个函数接受一个整数列表作为参数,并且我想查看列表中是否有5个可被2整除的项目。

So for example, if I call the function "find_numbers" with this call: 因此,例如,如果通过此调用调用函数“ find_numbers”:

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

it should return: 它应该返回:

   True

because the list has 5 items that are divisible by two (4,6,8,66 and 22) otherwise it should return false . 因为列表中有5个项目可被两个(4、6、8、66和22)整除,否则应返回false

How would I go about doing this? 我将如何去做呢?

Thanks for the help! 谢谢您的帮助!

Note : I need to use recursion for later in the program, I know using a loop would be easier but it will be more of a headache for me later on (Again, thank you very much). 注意 :我需要在程序的后面使用递归,我知道使用循环会更容易,但是以后对我来说将是更令人头疼的(再次,非常感谢)。

Edit: apologies for misreading. 编辑:道歉误读。 It is now recursive even though I'm having trouble figuring out why you would need this. 现在,即使我在弄清楚为什么需要此功能时也遇到问题,它仍是递归的。

You iterate through the list until you find a n numbers where modulo 2 == 0 . 您遍历列表,直到找到n modulo 2 == 0数字。 % is the python modulo operator. %是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

This will return True if and only if x meets the condition enough times. 当且仅当x满足条件足够的次数时,它将返回True。 It will throw an error if it iterates to an index on the list where an inoperable value is located (eg a str ). 如果迭代到无法操作的值所在的列表中的索引(例如str ),则将引发错误。 It will catch the IndexError so that it can take short lists as in the last example. 它将捕获IndexError,以便可以像上一个示例中那样列出简短列表。


Explanation: The important thing to remember here is that the final case ramifies up the call stack. 说明:这里要记住的重要一点是,最后一种情况会扩大调用堆栈。 So if the last call returns True | False 因此,如果最后一次调用返回True | False True | False and each successive call before that can only return an error (the str input case I mentioned) or True | False | Another recursive call True | False和之前的每个后续调用只能返回错误(我提到的str输入大小写)或True | False | Another recursive call True | False | Another recursive call True | False | Another recursive call then we can expect the final case to be one one of those. 然后再进行True | False | Another recursive call我们可以预期最终情况就是其中之一。

Another nice thing about this is that it stops when it finds the fifth match so you save iterating through the list any further, I think. 另一个有趣的事情是,它会在找到第五个匹配项时停止,因此我认为您可以进一步保存对列表的迭代。 Perhaps that's the reason OP wanted recursion. 也许这就是OP想要递归的原因。

Here is another approach that keeps the records of the list elements who are divisible by 2: 这是另一种方法,可以保留被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))

Output: 输出:

[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 # []

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过递归获得数字列表的总和,不包括可被 3 和 7 整除的整数? - How to get the sum of a list of numbers excluding integers that are divisible by 3 and 7 with recursion? 如何使用'for循环'function并找到可被7整除的数字python? - How to use the 'for loop' function and find numbers divisible by 7, python? 如何创建一个函数以查找可以被7整除但不能被5整除的数字 - How to create a function to find numbers divisible by 7 but not by 5 Python列表推算-对于所有1-1000的数字,请使用列表推算来查找任何可被整数整除的最高个位数 - Python List Comprehensions -For all the numbers 1-1000, use a list comprehension to find the highest single digit any of the numbers is divisible by 查找数字可被5或3整除的程序 - Programs that Find Numbers Divisible by 5 or 3 我如何有效地找出有多少数不能从素数列表中整除? - How do I efficiently find out how many numbers are not divisible from a list of primes? 如何找到一个程序,它将添加只能被某些数字整除的数字总和 - How to find a program that will add the sums of numbers that are divisible by only certain numbers 如何使用递归查找列表中偶数的总和? - How to find sum of even numbers in a list using recursion? 如何使用递归在列表中找到偶数的乘积? - how to find the product of even numbers in a list using recursion? 查找数字是否可被输入数字整除 - find if a number divisible by the input numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM