首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法生成计算树中非终端节点的程序

无法生成计算树中非终端节点的程序
EN

Stack Overflow用户
提问于 2020-06-02 12:00:08
回答 2查看 73关注 0票数 0

这是一个语法树,它看起来像这样的代码形式

我的程序应该是计算树上非终端节点的数目。想法是每棵树都是两个元组。在第一位置上,将母节点作为字符串站立,在第二位置上,如果存在终端节点,则在第二位置上站立字符串,或者在具有母节点的子树的列表上。它们是递归的。程序应该计数非终端节点的数量,。因此,结果应该只是一些非终端节点,例如9。

据我所知,我应该使用递归来完成这个任务。但是,有一些事情我做的不对,使我的程序工作。我的代码是:

代码语言:javascript
运行
复制
tuple_list = []
second_tuple_elements = [a_tuple[1] for a_tuple in tuple_list]
print(second_tuple_elements)
def nonterminal(count):

    if second_tuple_elements == type(""):

        return 1

    if second_tuple_elements == type([]):
        for element in list:
            if element == type (""):
                return 1
            nonterminal = second_tuple_elements + element
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-02 14:30:10

这里有一个解决方案:

代码语言:javascript
运行
复制
def count_nodes(tree):
    count = 0

    if isinstance(tree, str):
        return 0
    node, rest = tree 
    count +=1 
    for subtree in rest: 
        count += count_nodes(subtree)

    return count
票数 1
EN

Stack Overflow用户

发布于 2020-06-02 15:30:26

你的程序里没有递归调用-

代码语言:javascript
运行
复制
def node_count(node):
  mother, children = node       # get parts of node tuple
  if isinstance(children, str): # mother of terminal node
    return 1                    # return 1 to count this mother
  else:                         # mother of non-terminal node
    return 1 + \                # return 1 plus...
      sum(node_count(x) for x in children) # the sum of each child node_count 

my_tree = \
  ('S', [('NP', [('ART', 'die'), ('N', 'Katze')]), ('VP', [('V', 'jagt'), ('NP', [('ART', 'die'), ('N', 'Vögel')])])])

print(node_count(my_tree))
# 9
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62151524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档