Невозможно сгенерировать дерево Фибоначчи с помощью объектно-ориентированной проги. в Python.
I am a starter & want to integrate dfs code with Fibonacci series generating code. The Fibonacci code too runs as dfs, with calls made from left to right. The integration is incomplete still. I have two issues : (i) Unable to update 'path' correctly in fib(), as the output is not correctly depicting that. (ii) Stated in fib() function below, as comment. ----- Have one more issue that is concerned with program's working: (iii) On modifying line #16 to: stack = root = stack[1:]; get the same output as before. import sys count = 0 root_counter = 0 path=1 inf = -1 node_counter = 0 root =0 def get_depth_first_nodes(root): nodes = [] stack = [root] while stack: cur_node = stack[0] stack = stack[1:] nodes.append(cur_node) for child in cur_node.get_rev_children(): stack.insert(0, child) return nodes def node_counter_inc(): global node_counter node_counter = node_counter + 1 class Node(object): def __init__(self, id_,path): self.id = node_counter_inc() self.children = [] self.val = inf #On instantiation, val = -1, filled bottom up; #except for leaf nodes self.path = path def add_child(self, node): self.children.append(node) def get_children(self): return self.children def get_rev_children(self): children = self.children[:] children.reverse() return children def fib(n, level, val, path): global count, root_counter, root print('count :', count, 'n:', n, 'dfs-path:', path) count += 1 if n == 0 or n == 1: path = path+1 return n if root_counter == 0: root = Node(n, path) root_counter = 1 else: #cur_node.add_child(Node(n, path)) -- discarded for next(new) line root.add_child(Node(n, path)) tmp = fib(n-1, level + 1,inf, path) + fib(n-2, level + 1,inf,path+1) #Issue 2: Need update node's val field with tmp. #So, need suitable functions in Node() class for that. print('tmp:', tmp, 'level', level) return tmp def test_depth_first_nodes(): fib(n,0,-1,1) node_list = get_depth_first_nodes(root) for node in node_list: print(str(node)) if __name__ == "__main__": n = int(input("Enter value of 'n': ")) test_depth_first_nodes()
Что я уже пробовал:
Помимо вышеприведенной попытки, также расточительно пытались использовать cur_node (вместо root) в fib(). Но это не сработало, так как оно было принято за целое число. Я внес следующие изменения в вышеприведенную программу : 1. инициализировал ее на '0' как g.v.; 2. объявил ее как g.v.in обе функции: fib() и get_depth_first_nodes(); 3. комментируя строку #53 вместо строки #52.