[英]What is best: Global Variable or Parameter in this python function?
我對以下代碼有疑問,但我想適用於不同的功能。 這個 function 在給定 Graph、源節點和結束節點的情況下計算 DAG 的最大路徑及其長度。
為了跟蹤已經計算的遞歸距離,我使用“max_distances_and_paths”變量,並在每次遞歸時更新它。
最好將其保留為 function 參數(通過遞歸輸入和輸出)還是使用全局變量並在 function 之外對其進行初始化?
如何避免在外部調用 function 時返回此參數(即它必須跨遞歸輸出,但我不關心它的值,外部)?
比這樣做更好的方法:LongestPath(G, source, end)[0:2]??
謝謝
# for a DAG computes maximum distance and maximum path nodes sequence (ordered in reverse).
# Recursively computes the paths and distances to edges which are adjacent to the end node
# and selects the maximum one
# It will return a single maximum path (and its distance) even if there are different paths
# with same max distance
# Input {Node 1: adj nodes directed to Node 1 ... Node N: adj nodes directed to Node N}
# Example: {'g': ['r'], 'k': ['g', 'r']})
def LongestPath(G, source, end, max_distances_and_paths=None):
if max_distances_and_paths is None:
max_distances_and_paths = {}
max_path = [end]
distances_list = []
paths_list = []
# return max_distance and max_path from source to current "end" if already computed (i.e.
# present in the dictionary tracking maximum distances and correspondent distances)
if end in max_distances_and_paths:
return max_distances_and_paths[end][0], max_distances_and_paths[end][1], max_distances_and_paths
# base case, when end node equals source node
if source == end:
max_distance = 0
return max_distance, max_path, max_distances_and_paths
# if there are no adjacent nodes directed to end node (and is not the source node, previous case)
# means path is disconnected
if len(G[end]) == 0:
return 0, [0], {"": []}
# for each adjacent node pointing to end node compute recursively its max distance to source node
# and add one to get the distance to end node. Recursively add nodes included in the path
for t in G[end]:
sub_distance, sub_path, max_distances_and_paths = LongestPath(G, source, t, max_distances_and_paths)
paths_list += [[end] + sub_path]
distances_list += [1 + sub_distance]
# compute max distance
max_distance = max(distances_list)
# access the same index where max_distance is, in the list of paths, to retrieve the path
# correspondent to the max distance
index = [i for i, x in enumerate(distances_list) if x == max_distance][0]
max_path = paths_list[index]
# update the dictionary tracking maximum distances and correspondent paths from source
# node to current end node.
max_distances_and_paths.update({end: [max_distance, max_path]})
# return computed max distance, correspondent path, and tracker
return max_distance, max_path, max_distances_and_paths
由於幾個原因,通常避免使用全局變量(請參閱為什么全局變量是邪惡的? )。 我建議在這種情況下發送參數。 但是,您可以定義一個更大的 function 來容納遞歸 function。 這是我為階乘代碼編寫的一個簡單示例:
def a(m):
def b(m):
if m<1:return 1
return m*b(m-1)
n = b(m)
m=m+2
return n,m
print(a(6))
這將給出: (720, 8)
。 這證明即使您在遞歸 function 中使用相同的變量名,您傳遞給較大的 function 的變量名也不會改變。 在您的情況下,您只想按照我的示例返回n
。 我只返回了一個編輯過的m
值,以表明即使a
和b
函數都將m
作為輸入,Python 將它們分開。
一般來說,我會說避免使用全局變量。 這是因為如果您的代碼庫變得更復雜一些,這會使您的代碼更難閱讀並且通常更難以調試。 所以這是一個很好的做法。
我會使用一個助手 function 來初始化你的遞歸。
def longest_path_helper(G, source, end, max_distances_and_paths=None):
max_distance, max_path, max_distances_and_paths = LongestPath(
G, source, end, max_distances_and_paths
)
return max_distance, max_path, max_distances_and_paths
附帶說明一下,在 Python 中,編寫不帶大寫字母並用下划線分隔的函數是慣例,類使用不帶下划線的 Capicalized。 所以使用def longest_path():
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.