什么会使布尔返回值在返回后发生变化?

时间:2013-11-01 13:56:40

标签: python recursion return

在这个递归代码中,我正在获得正确返回True的函数,但随后又继续执行1步并将返回值更改为“None”。我相信我不理解返回值。有人能告诉我为什么会这样吗?提前谢谢。

-

def nestedListContains(NL, target):
   for i in range(0, len(NL)):
      if type(NL[i]) == int:
         if NL[i] == target:
            return True
         elif i == (len(NL) - 1):
            return False
      elif type(NL[i]) != int:
         nestedListContains(NL[i], target)

nestedListContains([[9, 4, 5], [3, 8]], 3)   #Test Case#

3 个答案:

答案 0 :(得分:1)

您的代码有三个问题;首先,你对递归调用的结果什么都不做。其次,您应该使用isinstance()来检查值是否属于某种类型,而不是type(ob) ==。第三,而不是使用range()并检查i以查看是否达到了最后一个值,如果没有找到任何内容,则在循环后返回False。

总计:

def nestedListContains(NL, target):
    for value in NL:
        if isinstance(value, int):
            test = value == target
        else:
            # value is not an int, so it's a list
            test = nestedListContains(value, target)
        if test:
            return True  # found target

    return False  # We finished the loop without finding target

如果NL根本不是列表,则会抛出TypeError。这可能是一个比isinstance()更好的检查 - 如果它可以迭代然后它是一个列表,如果迭代抛出一个TypeError,那么我们应该与target进行比较。我还会使命名更加标准化:

def nested_list_contains(nested_list, target):
    try:
        for value in nested_list:
            if nested_list_contains(value, target):
                return True
        return False
    except TypeError:
        # It's a single value
        return nested_list == target

但还有更好的方法。我们真正想做的是展平嵌套列表,并检查目标是否在其中。我们可以将上面的内容变成一个递归地展平迭代的生成器:

def flatten_nested_list(nested_list):
    try:
        for v in nested_list:
            for flattened in flatten_nested_list(v):
                yield flatten
    except TypeError:
        yield nested_list

def nested_list_contains(nested_list, target):
    return target in flatten_nested_list(nested_list)

答案 1 :(得分:0)

要使用递归,您必须返回递归结果:

def nestedListContains(NL, target):
   for i in range(0, len(NL)):
      if type(NL[i]) == int:
         if NL[i] == target:
            return True
         elif i == (len(NL) - 1):
            return False
      elif type(NL[i]) != int:
         #you missed the return for the recursive case
         ret = nestedListContains(NL[i], target)
         if(type(ret) == bool): #ensure we have an actual result and not a fall through
             return ret

答案 2 :(得分:-1)

要详细说明之前的答案,当您到达函数末尾而不返回特定值时,会得到None

  def func():
     ... do something ...

相当于:

  def func():
     ... do something ...
     return None

如果你传入一个空NL,这仍然会发生,因为循环后没有return语句。

(另外,isinstance(value, int)是检查某事物类型的首选方式)