在列表中计算奇数的Python方法
这是我作业的一部分,我快要找到最终答案了,但还差一点。我需要写一个函数,用来计算列表中的奇数个数。
创建一个递归函数 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])
你能帮我解释一下我缺少了什么吗?前两个测试都能正常工作,但我无法通过最后两个测试。谢谢!
10 个回答
2
def count_odd(L):
return (L[0]%2) + count_odd(L[1:]) if L else 0
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
4
因为这是作业,所以这里有一段伪代码,它只是用来计算一个列表的元素数量:
function count (LIST)
if LIST has more items
// recursive case.
// Add one for the current item we are counting,
// and call count() again to process the *remaining* items.
remaining = everything in LIST except the first item
return 1 + count(remaining)
else
// base case -- what "ends" the recursion
// If an item is removed each time, the list will eventually be empty.
return 0
这段代码和作业要求的内容非常相似,但你需要把它转换成Python语言,并且要搞清楚正确的递归逻辑。
祝你编码愉快。
1
切片可以吗?我觉得这并不是很像递归,但我想整个做法有点不符合常规的写法(也就是说,在Python中这种递归方式不太常见):
def countOdd(l):
if l == list(): return 0 # base case, empty list means we're done
return l[0] % 2 + countOdd(l[1:]) # add 1 (or don't) depending on odd/even of element 0. recurse on the rest
x%2
对于奇数来说是 1
,对于偶数来说是 0
。如果你对这个不太舒服或者不太理解,可以用下面的代码替换上面最后一行:
thisElement = l[0]
restOfList = l[1:]
if thisElement % 2 == 0: currentElementOdd = 0
else: currentElementOdd = 1
return currentElementOdd + countOdd(restOfList)
顺便说一下,这个其实是挺递归的,如果你把这个交给老师看看,看看他怎么说 =P
>>> def countOdd(l):
... return fold(lambda x,y: x+(y&1),l,0)
...
>>> def fold(f,l,a):
... if l == list(): return a
... return fold(f,l[1:],f(a,l[0]))