The following Python program generates Motzkin trees. They are made of leaves, u
ID: 3745659 • Letter: T
Question
The following Python program generates Motzkin trees. They are made of leaves, unary nodes (nodes with one branch) and binary nodes (nodes with two branches). # Motzkin tree of size n def mot (n) : if n==0 : yield 'leaf' else : for m in mot(n-1) : yield ('unary',m) for k in range(0,n-1) : for l in mot(k) : for r in mot(n-2-k) : yield ('binary',l,r) def test(m) : for n in range(m) : list(map(print,list(mot(n)))) Write a Python program that generates the same output without using the "yield" statement. The program may use Python arrays, tuples, dictionaries but no classes. To facilitate grading, the program should provide a function similar to "test(m)", that given an natural number m, prints out all trees of size less than m, one per line, in the same format.
Explanation / Answer
def motzkin(n) :
if n==0:
dp = [None] * (n+1)
#fundamental case
dp[0] = dp[1] = 1;
add = ['a', 'b', 'c']
add.append('leaf') #using array to deine
print(add)
for i in month(n-1):
# Finding i-th Motzkin number.
while i <= n(unary node) :
dp[i] = ((2 * i + 1) * dp[i - 1] +
(3 * i - 3) * dp[i - 2]) / (i + 2);
i = i + 1
return dp[n];
#using python tuple
for m in mot(n-1) :
my_tuple = ('u,n,a,r,y',m)
for k in range(0,n-1) :
for l in mot(k) :
print(my_tuple.count('unary'))
my_tuple = ('b,i,n,a,r,y',l,r)
for r in mot(n-2-k) :
print(my_tuple.index('binary',l,r))
('binary',l,r)
# Driver code
n = 8
print( motzkin(n) )
#using python dictionary
my_dict = {'leaves':'unary', 'binary':size n}
my_dict['m'] = "output"
print(my_dict)
def check(m) :
for n in range(m) : //provides a natural number m
print.trees([<<m]) //print trees less than m
list(map(print,list(mot(n))))
leaves = {}.fromnodes(['unary','binary'], 0)
for branch in nodes.leaves():
list(map(print,list(mot(n))))
print(list(mot))
Hope you understand and this helps you.All the best