Issue
This is a syntactic tree and it looks like this in the form of code
My program is supposed to count the number of non-terminal nodes on that tree. The idea is that every tree is a 2 tuple. On the first position stands the mother node as a string and on the second position stands either a string if there is a terminal node or a list with daughter trees of the mother node. They are recursive. The program should count the number of nonterminal nodes. so the result should just be a number of nonterminal nodes, e.g. 9.
So far as I have understood, I should do this using recursion. But there are some things that I fail to do correctly to make my programm work. My code is:
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
Solution
Here's a solution:
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
Answered By - Roy2012
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.