一种递归函数,它返回一个in

2024-04-25 08:11:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我不知道为什么我的功能不起作用

有人能告诉我怎么修吗?非常感谢。在


Tags: ofin列表for参数lenifdef
3条回答

不使用嵌套函数调用的结果。您可能应该分别用c += nested_count(l,a)c += nested_count(x,a)替换这些行。在

在迭代列表时不应该改变列表,并且需要从递归调用返回结果。通过检查l的类型,如果它是int,然后返回{},告诉它是否与{}匹配,可以大大简化函数。如果l是一个列表,只需递归地调用其“items”上的nested_count,结果是{}:

def nested_count(l, a):
    # Base case
    if type(l) == int:
        return l == a
    return sum(nested_count(x, a) for x in l)

您没有将nested_count结果添加到c

def nested_count(lst, l):
    c = 0
    for i in lst:
        if i == l:
            c += 1
        elif type(i) == list:
            c += nested_count(i, l)
    return c

另外,最好用for遍历list。在

相关问题 更多 >