def count_even(obj):
"""
Return the number of even numbers in obj or sublists of obj
if obj is a list. Otherwise, if obj is a number, return 1
if it is an even number and 0 if it is an odd number.
@param int|list obj: object to count even numbers from
@rtype: int
>>> count_even(3)
0
>>> count_even(16)
1
>>> count_even([1, 2, [3, 4], 5])
2
"""
count = 0
if isinstance(obj, int):
if obj % 2 == 0:
return 1
else:
return 0
else:
for i in obj:
count += count_even(i)
return new
我不明白在最后第二行“count+=count_-even(I)”,“recursion”是如何访问[1,2,[3,4],5]的嵌套列表[3,4]。在
for循环不会遍历每一项{i=0(1),i=1(2),i=2([3,4]),i=3(5)},寻找一个int,并且没有if语句触发器[3,4],因为它是一个列表吗?在
该函数能够访问嵌套列表}的奇数/均匀度。在
[3, 4]
,因为正如您所述,值[3, 4]
跳过了第一个if
(因为[3, 4]
不是int
),然后执行else。在else中,您将在[3, 4]
上得到另一个循环,然后检查3
和{这里有一条线索可以帮助你理清思路:
相关问题 更多 >
编程相关推荐