如何打印出递归决策树?

时间:2014-04-09 00:59:24

标签: python recursion tree

我需要打印出一个递归树,如下所示。我希望这个代码是通用的,适用于其他树。我只是弄清楚如何打印递归树。

使用此词典的PrintDt(Tennis),例如:

Tennis = ['skurple type', {'gloomp': 'Yes', 'murket': ['which murket', {'grabe': ['grabetime', {'sproon': 'No', 'midnort': 'Yes'}], 'carfer': 'Yes', 'glambit': 'No'}], 'snarzle': ['froovencity level', {'granky': 'No', 'slipely': 'Yes'}]}]

输出应该是:

在skurple类型上分割

If skurple type == gloomp
    Return: Yes
If skurple type == murket
    Split on which murket
    If which murket == grabe
        Split on grabetime
        If grabetime == sproon
            Return: No
        If grabetime == midnort
            Return: Yes
    If which murket == carfer
        Return: Yes
    If which murket == glambit
        Return: No
If skurple type == snarzle
    Split on froovencity level
    If froovencity level == granky
        Return: No
    If froovencity level == slipely
        Return: Yes

1 个答案:

答案 0 :(得分:1)

看起来这样可行:

def PrintDt(tree, depth=0):
    if type(tree) == str:
        print depth*'\t', 'Return:', tree
    else:
        print depth*'\t', 'Split on', tree[0]
        for value in tree[1].keys():
            print depth*'\t', 'If', tree[0], '==', value 
            PrintDt(tree[1][value], depth + 1)

示例:

>>> def PrintDt(tree, depth=0):
...     if type(tree) == str:
...         print depth*'\t', 'Return:', tree
...     else:
...         print depth*'\t', 'Split on', tree[0]
...         for value in tree[1].keys():
...             print depth*'\t', 'If', tree[0], '==', value 
...             PrintDt(tree[1][value], depth + 1)
... 
>>> Tennis = ['skurple type', {'gloomp': 'Yes', 'murket': ['which murket', {'grabe': ['grabetime', {'sproon': 'No', 'midnort': 'Yes'}], 'carfer': 'Yes', 'glambit': 'No'}], 'snarzle': ['froovencity level', {'granky': 'No', 'slipely': 'Yes'}]}]
>>> PrintDt(Tennis)
 Split on skurple type
 If skurple type == gloomp
    Return: Yes
 If skurple type == murket
    Split on which murket
    If which murket == grabe
        Split on grabetime
        If grabetime == sproon
            Return: No
        If grabetime == midnort
            Return: Yes
    If which murket == carfer
        Return: Yes
    If which murket == glambit
        Return: No
 If skurple type == snarzle
    Split on froovencity level
    If froovencity level == granky
        Return: No
    If froovencity level == slipely
        Return: Yes