为什么我的递归函数返回“None”?

时间:2013-06-24 23:31:35

标签: python recursion dictionary scope

所有

我在Python中有一个字典列表字典。这代表了亲子关系。给一个孩子,我想归还父母。

这是我的收藏:

tree = { u'one' : [ { u'two' : [ { u'three' : [] }, { u'four' : [] } ] }, { u'five' : [ { u'six' : [] } ] } ] }

正如你所看到的,“一个”有孩子“两个”和“五个”,“两个”有孩子“三个”和“四个”,“三个”没有孩子,等等。

以下代码正确地解决了给定子项的父级:

def find_parent(search_term,collection,parent=None):
  if isinstance(collection,dict):
    for key,value in collection.iteritems():
      if key.lower() == search_term.lower():
        print "the parent of %s is %s" % (key,parent)
        return parent
      if isinstance(value,list):
        for v in value:
          find_parent(search_term,v,key)

my_child = "two"
my_parent = find_parent(my_child,tree)

该函数中的print语句始终打印正确的值。但是,如果我尝试访问my_parent,其值始终为“None”。这里的东西必须超出范围。我只是无法解决如何解决它。

感谢。

2 个答案:

答案 0 :(得分:4)

您还需要返回递归调用值:

if isinstance(value,list):
    for v in value:
        parent = find_parent(search_term,v,key)
        if parent is not None: return parent

如果没有忽略return,则丢弃递归搜索返回值。

添加了return的演示:

>>> def find_parent(search_term,collection,parent=None):
...   if isinstance(collection,dict):
...     for key,value in collection.iteritems():
...       if key.lower() == search_term.lower():
...         print "the parent of %s is %s" % (key,parent)
...         return parent
...       if isinstance(value,list):
...         for v in value:
...           parent = find_parent(search_term,v,key)
...           if parent is not None: return parent
... 
>>> my_child = "two"
>>> tree = { u'one' : [ { u'two' : [ { u'three' : [] }, { u'four' : [] } ] }, { u'five' : [ { u'six' : [] } ] } ] }
>>> find_parent(my_child,tree)
the parent of two is one
u'one'

答案 1 :(得分:3)

您递归调用find_parent(search_term,v,key)但忽略返回的值。我建议您找到一个好的Python IDE并学习使用它的调试功能。这将极大地帮助您跟踪此类逻辑错误。

相关问题