如果我有一个使用以下形式的元组列表 构建最小堆结构的函数: [(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))]
提前致谢。
慕神8447489
哔哔one
相关分类