def nested_count(l : 'any nested list of int', a : int) -> int:
c = 0
while len(l) != 0:
for x in l:
if type(x) == int:
if x == a:
c = c + 1
l.remove(x)
nested_count(l,a)
else:
continue
elif type(x) == list:
nested_count(x,a)
return c
此函数传递了一个嵌套的int列表和一个int作为参数;它返回单个int参数在嵌套列表参数中出现的次数,例如:
^{pr2}$返回5
我不知道为什么我的功能不起作用
有人能告诉我怎么修吗?非常感谢。在
不使用嵌套函数调用的结果。您可能应该分别用
c += nested_count(l,a)
和c += nested_count(x,a)
替换这些行。在在迭代列表时不应该改变列表,并且需要从递归调用返回结果。通过检查},告诉它是否与{}匹配,可以大大简化函数。如果}:
l
的类型,如果它是int
,然后返回{l
是一个列表,只需递归地调用其“items”上的nested_count
,结果是{您没有将
nested_count
结果添加到c
:另外,最好用for遍历list。在
相关问题 更多 >
编程相关推荐