如果我有一個使用以下形式的元組列表 構(gòu)建最小堆結(jié)構(gòu)的函數(shù): [(vertex),length,(another_vertex),...........],我將該函數(shù)寫入采用兩個輸入:堆結(jié)構(gòu)和先前形式的稱為三元組的新元素。它應(yīng)該根據(jù)“(頂點)”從添加的三元組中構(gòu)建沒有重復(fù)項的堆,并根據(jù)“長度”以升序方式構(gòu)建堆,我將其編寫如下: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我的問題是使用以下兩種方法調(diào)用函數(shù)有什么區(qū)別: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))因為在第二種方法中該函數(shù)的行為不正確:正確的輸出 - 第一次調(diào)用:新堆是: [((2, 3), 0.9, (1, 0))]新堆是: [((7, 2), 0.3 , (2, 2)), ((2, 3), 0.9 , (1, 0))]錯誤的輸出 - 第二次調(diào)用:新堆是: [((2, 3), 0.9, (1, 0))]新堆是: [((2, 3), 0.9 , (1, 0)), ((7, 2), 0.3 , (2, 2))]提前致謝。
查看完整描述