python - 如何在 Python 中将对象类的实例化定义为全局变量?
问题描述
我是初学者,想将 dfs 代码与斐波那契数列生成代码集成。斐波那契代码也作为 dfs 运行,调用从左到右。整合仍然不完整。
我有两个问题:
(i) 无法在 fib() 中正确更新“路径”,因为输出没有正确描述这一点。
(ii) 在下面的 fib() 函数中说明,作为评论。
附言
还有一个与程序工作有关的问题:
(iii) 将第 16 行修改为:stack = root = stack[1:]; 得到和以前一样的输出。
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 __repr__(self):
return "Node: [%s]" % self.id
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
root.add_child(Node(n, path))
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()
想从这里添加代码的想法。
解决方案
回答第一个问题:
这个特定问题中的路径是一个整数。它是以贪婪的dfs方式从根到叶子的路径编号。
这可以通过让 path 成为全局变量而不是 fib 函数的输入来实现。每当我们到达叶子时,我们就会增加路径计数。
我还修改了 fib 函数以返回一个节点而不是一个数字。
import sys
count = 0
root_counter = 0
path=1
inf = -1
node_counter = 0
root = None
def node_counter_inc():
global node_counter
node_counter = node_counter + 1
print("node_counter:", node_counter)
return node_counter
class Node(object):
def __init__(self, id__,path):
print("calling node_counter_inc() for node:", n )
try:
self.id = int(node_counter_inc())
except TypeError:
self.id = 0 # or whatever you want to do
#self.id = int(node_counter_inc())
self.val = inf #On instantiation, val = -1, filled bottom up;
#except for leaf nodes
self.path = path
self.left = None
self.right = None
def __repr__(self):
return "Node" + str(self.id) + ":"+ str(self.val)
def fib(n, level, val):
# make fib returns a node rather than a value
global count, root_counter, root, path
print('count :', count, 'n:', n, 'dfs-path:', path)
count += 1
if n == 0 or n == 1:
path = path+1
new_Node = Node(n, path)
new_Node.val = n
return new_Node
#root.add_child(new_Node)
# return new_node
#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) + fib(n-2, level + 1,inf)
#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
ans = Node(n, path)
ans.left = fib(n-1, level + 1, inf)
ans.right = fib(n-2, level + 1, inf)
ans.val = ans.left.val + ans.right.val
print("the node is", ans.id, "with left child", ans.left.id, "and right child", ans.right.id)
print("the corresponding values are", ans.val, ans.left.val, ans.right.val)
return ans
def test_depth_first_nodes():
ans = fib(n,0,-1)
print("The answer is", ans.val)
#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()
推荐阅读
- rest - 最合适的 Azure 服务进行数以千计的出站 API 调用
- dialogflow-es - 在 Dialogflow 中使用 $Knowledge.Answer[2] 或 $Knowledge.Answer[3]
- r - 从文本文件中读取 R 表时的奇怪行为
- hyperledger-fabric - 有时启动网络或升级网络时使用 Hyperledger Composer 与 HyperLedger Fabric(分布式)交互失败
- javascript - 表单提交后删除按钮样式
- docker - docker compose nginx代理不重定向
- neo4j - Neo4j 查询错误地返回 null
- sql - SQL 左连接与 JOIN 条件中的过滤器与 WHERE 子句中的过滤器
- javascript - 如何在 jQuery 集合中选择元素
- php - 在 codeigniter 项目中使用 Ruler 库