如果我有一個使用以下形式的元組列表 構建最小堆結構的函數: [(vertex),length,(another_vertex),...........],我將該函數寫入采用兩個輸入:堆結構和先前形式的稱為三元組的新元素。它應該根據“(頂點)”從添加的三元組中構建沒有重復項的堆,并根據“長度”以升序方式構建堆,我將其編寫如下:def heap_add_or_replace(heap, triplet): heap.append(triplet) # Sorting according to the first element of every triplet to have duplicates get next to each other vertexSort = sorted(heap, key = lambda x: x[0]) # Sorting according to the distance in ascending manner lenSort = sorted(vertexSort, key = lambda x: x[1]) # Function to remove duplicates def remvDuplicate(struct): check = set() result = [] for i in struct: if i[0] not in check: result.append(i) check.add(i[0]) return result # Setting the final return value heap = remvDuplicate(lenSort)return heap我的問題是使用以下兩種方法調用函數有什么區別:triplet_heap = list()a = heap_add_or_replace(triplet_heap,((2,3),0.9,(1,0)))print("the new heap is: " + str(a))b = heap_add_or_replace(triplet_heap,((7,2),0.3,(2,2)))print("the new heap is: " + str(b))和,new_heap = list()heap_add_or_replace(new_heap,((2,3),0.9,(1,0)))print("the new heap is: " + str(new_heap))heap_add_or_replace(new_heap,((7,2),0.3,(2,2)))print("the new heap is: " + str(new_heap))因為在第二種方法中該函數的行為不正確:正確的輸出 - 第一次調用:新堆是: [((2, 3), 0.9, (1, 0))]新堆是: [((7, 2), 0.3 , (2, 2)), ((2, 3), 0.9 , (1, 0))]錯誤的輸出 - 第二次調用:新堆是: [((2, 3), 0.9, (1, 0))]新堆是: [((2, 3), 0.9 , (1, 0)), ((7, 2), 0.3 , (2, 2))]提前致謝。
2 回答

慕神8447489
TA貢獻1780條經驗 獲得超1個贊
在第一種情況下,即“正確的情況”,您正在查看函數的返回值heap_add_or_replace
。
在第二種情況下,即“不正確的情況”,您將查看list
每次將原始數據傳遞給heap_add_or_replace
函數時會發生什么情況。
在該函數中,您在第一次進行排序時heap_add_or_replace
復制輸入。list
排序的結果以及此后所做的所有操作都不會反映在原始列表中。因此,您傳入的原始列表永遠不會被排序或過濾重復項。這就是兩個案例不同的原因。

嗶嗶one
TA貢獻1854條經驗 獲得超8個贊
以下是與您的兩種情況類似的情況:
a = []
def f(l):
l.append(0) #affect global variable a
l = 5 #new local variable created inside the function
return l #return l = 5!
#first case
b = f(a) #b is assigned value from return l (5)
#second case
print(a) #printing global variable not result from function ([0])
添加回答
舉報
0/150
提交
取消