【发布时间】:2021-04-14 14:52:14
【问题描述】:
这是我的家庭作业的一部分,我接近最终答案,但还没有。我需要编写一个计算列表中奇数的函数。
创建一个递归函数 count_odd(l),它的唯一参数是整数列表。该函数将返回奇数列表元素的数量,即不能被 2 整除。\
>>> print count_odd([])
0
>>> print count_odd([1, 3, 5])
3
>>> print count_odd([2, 4, 6])
0
>>> print count_odd([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144])
8
这是我目前所拥有的: #- 递归函数 count_odd -#
def count_odd(l):
"""returns a count of the odd integers in l.
PRE: l is a list of integers.
POST: l is unchanged."""
count_odd=0
while count_odd<len(l):
if l[count_odd]%2==0:
count_odd=count_odd
else:
l[count_odd]%2!=0
count_odd=count_odd+1
return count_odd
#- test harness
print count_odd([])
print count_odd([1, 3, 5])
print count_odd([2, 4, 6])
print count_odd([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144])
你能帮忙解释一下我缺少什么吗?前两个测试工具工作正常,但我无法获得最后两个。谢谢!
【问题讨论】:
-
你错过了递归。
-
你能帮助解释我如何进行递归吗?我是 python 新手,我们的教授并没有很好地解释递归。
-
Recursion 不是 Python 特定的概念。一般来说,当你的函数体调用函数本身作为计算的一部分时,你就是在进行递归。
-
另外,即使这个函数没有递归,逻辑也是有缺陷的。尝试使用
[2,4,6]参数一次一行地遍历它,看看是否能发现错误。