自我调用的递归

时间:2016-11-04 08:36:43

标签: python dictionary recursion

早上好/白天/黑夜,SO社区。这是我几天前碰到的一个问题,但仍然没有答案。

我有一本字典:

maindict = {
1Class: [2Class, 3Class],
2Class: [2-1Class, 2-2Class, 2-3Class],
3Class: [3-1Class],
2-1Class: [],
2-2Class: [2-2-1Class]
}

等等。

我也知道哪个类是主要的,例如它将是1Class。我把它保存在:     mainclass =(0,1Class)

我有一个函数,它在给定类的maindict中查找子类,并返回元组字典:

def getSubClass(maindict, class):
    MAGIC HERE
    return result

结果     getSubClass(maindict,mainclass) 将列表与元组:

  

[(1-1,2Class),(1-2,3Class)]

问题是我需要迭代所有类并为每个类获取子类。有些课程没有子类,有些则没有。所以对于测试我做了这个:

b = getSubClass(maindict, mainclass)
c = getSubClass(maindict, b)
d = getSubClass(maindict, c)
e = getSubClass(maindict, d)
f = getSubClass(maindict, e)
g = getSubClass(maindict, f)
h = getSubClass(maindict, g)
i = getSubClass(maindict, h)

和'我'是空的,这意味着我收集了所有课程。我还将每个c,d等附加到dict并验证输出是否正确。

现在我需要做的就是编写手动脚本的递归函数,但我只是坚持到这里。

1 个答案:

答案 0 :(得分:1)

看起来很简单。如果你想要的是一个列表Field f = fields.get(player.getPosition()); f.visit(player); // ... public abstract class Field { public abstract void visit(Player player); } // ... public class Luck extends Field { public void visit(Player player) { player.income(this.price); } } // ... public class Service extends Field { public void visit(Player player) { player.expense(this.price); } } ,那么你必须编辑你的[b,c,d,e,f,g,h]函数,如下所示:

getSubClass

将函数调用为:

def getSubClass(maindict, class, all_subclasses):
    if not class:
        #class is an empty tuple here
        return None
    MAGIC HERE

    # This will append the tuples in result to all_subclasses
    all_subclasses += result

    # Recursively calls getSubClass using the result computed
    # in the current function call.
    # If result is an empty tuple, then nothing will be added
    # to the all_subclasses list in the recursive call made
    getSubClass(maindict, result, all_subclasses)
    return result

所有子类元组都将出现在all_subclasses = [] getSubClass(maindict, mainclass, []) 列表