这是一个语法树,它看起来像这样的代码形式
我的程序应该是计算树上非终端节点的数目。想法是每棵树都是两个元组。在第一位置上,将母节点作为字符串站立,在第二位置上,如果存在终端节点,则在第二位置上站立字符串,或者在具有母节点的子树的列表上。它们是递归的。程序应该计数非终端节点的数量,。因此,结果应该只是一些非终端节点,例如9。
据我所知,我应该使用递归来完成这个任务。但是,有一些事情我做的不对,使我的程序工作。我的代码是:
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
发布于 2020-06-02 14:30:10
这里有一个解决方案:
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
发布于 2020-06-02 15:30:26
你的程序里没有递归调用-
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
https://stackoverflow.com/questions/62151524
复制相似问题