[英]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.