问题描述
def count(x,nxs,counter=0):
for e in nxs:
if type(e) == type([]):
count(x,e)
else:
if e == x:
counter += 1
return counter
print(count(2,[2,9,[2,1,13,13,2],8,[2,6]]))
这将打印1而不是4。
解决方法
您需要将计数器变量显式传递给递归函数
def count(x,nxs,counter=0):
for e in nxs:
if type(e) == type([]):
counter = count(x,e,counter)
else:
if e == x:
counter += 1
return counter
,
您需要使用递归调用的返回:
def count(x,counter=0):
for e in nxs:
if type(e) == type([]):
counter += count(x,e)
else:
if e == x:
counter += 1
return counter
由于counter
在本地使用,因此您只需将其从参数列表中删除:
def count(x,nxs):
counter = 0
for e in nxs:
if type(e) == type([]):
counter += count(x,e)
else:
if e == x:
counter += 1
return counter