【问题标题】:Python recursion, how come my function doesn't work?Python递归,我的函数怎么不起作用?
【发布时间】:2013-04-19 03:38:23
【问题描述】:

我正在尝试编写一个 Python 3 递归函数,它会告诉我一个整数是否在嵌套列表中。我不确定如何让我的代码在列表中找到它时返回True,如果在列表中找不到它则返回False。当我打印我的 for 循环的结果时,我得到了一堆

false
false
false
false
true
false
false
false

等等。但是,它返回 False,因为最后一次调用是 false,即使我希望它返回 true。我该如何解决这个问题?

这是我的代码:

def nestedListContains(NL, target):    
    if( isinstance(NL, int) ):
        return NL    

    for i in range(0, len(NL)):
       return ( nestedListContains(NL[i], target) == target )

    return False

这就是我的称呼

print(nestedListContains([[3], [4,5,7], [[[8]]]], 8))

编辑:这似乎对我有用,但似乎相当贫民窟:

def nestedListContains(NL, target):    
    if( isinstance(NL, int) ):
        if( NL == target ):
            return 1
        return 0

    x = 0

    for n in NL:
        x += nestedListContains(n, target) == 1        

    return x != 0

【问题讨论】:

  • 除了递归问题之外,您的基本情况似乎是错误的。当您到达int 时,如果它等于目标,则不会返回true,而是返回int 本身。这意味着最终,如果列表中有任何非零元素,您将返回 true,否则返回 false。
  • 您可能还想在这里考虑健壮性。如果 NL 包含任何非 int 非序列,它将引发TypeError,这可能很好——但如果它包含任何字符串,它将进入无限递归(最终会在遇到限制),这可能不太好。
  • 另外:为什么不直接删除int 检查,而只做if NL == target: return True?如果target 始终是int,这将产生完全相同的效果。但它允许您搜索其他类型(包括可以比较等于 int 但不是一个的对象)。而且更简单。
  • @abamert,你必须检查 NL 是否是可迭代的,否则 for 循环将失败。

标签: python python-3.x


【解决方案1】:

我的尝试:

def contains(lst, target):
    if isinstance(lst, int):
        return lst == target

    return any(contains(x, target) for x in lst)

【讨论】:

    【解决方案2】:

    不管是不是True,你return的结果。你可以这样做:

    def nestedListContains(NL, target):    
        if isinstance(NL, int):
            return NL == target
    
        for n in NL:
           result = nestedListContains(n, target)
    
           if result:
               return result
    
        return False
    

    【讨论】:

    • 你的意思是nestedListContains(n, target) == target
    • def nestedListContains(NL, target): if( isinstance(NL, int) ): if( NL == target ): return 1 return 0 x = 0 for n in NL: x += nestedListContains (n, target) == 1 return x != 0 你的方法仍然不适合我我现在正在以贫民窟的方式做事,但它似乎有效,有没有其他选择?
    • 它不适用于嵌套值:nestedListContains([[9, 4, 5], [3, 8]], 3)
    【解决方案3】:

    在@gatto 的解决方案中使用鸭子打字

    def contains(lst, target):
        try:
            return any(contains(x, target) for x in lst)        
        except TypeError:
            return lst == target
    

    【讨论】:

    • 如果lst 有一个字符串,可能会进入无限递归。我认为最好检查是否有__iter__属性。
    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 2018-04-02
    • 2014-04-03
    • 2017-01-13
    • 2023-02-07
    • 1970-01-01
    • 2014-10-15
    相关资源
    最近更新 更多