我目前正在上edx课程,任务之一是实现简单的min-heap。
必须使用一个元组列表来实现堆,该元组是不可变的,因此无法在原位置进行更改。
我的解决方案在下面,但是由于我是python的新手,我想知道一个经验丰富的程序员将如何实现它,但是在元组列表的现有约束下-无法使用其他数据结构。
def heap_add_or_replace(heap, triplet):
match=0
for tup in heap[:]:
if tup[0]==triplet[0]:
match+=1
if tup[1] > triplet[1]:
heap.remove(tup)
heap.append(triplet)
break
if match==0:
heap.append(triplet)
heap.sort(key=lambda x:x[1])
该课程的测试如下:
#
# AUTOGRADER TEST - DO NOT REMOVE
#
triplet_heap=list()
heap_add_or_replace(triplet_heap,((2,3),0.9,(1,0)))
print("the new heap is: "+str(triplet_heap))
heap_add_or_replace(triplet_heap,((7,2),0.3,(2,2)))
print("the new heap is: "+str(triplet_heap))
heap_add_or_replace(triplet_heap,((3,2),1,(2,2)))
print("the new heap is: "+str(triplet_heap))
print("the new heap is: "+str(triplet_heap))
heap_add_or_replace(triplet_heap,((7,2),0.2,(2,3)))
print("the new heap is: "+str(triplet_heap))
heap_add_or_replace(triplet_heap,((1,2),0.3,(2,3)))
print("the new heap is: "+str(triplet_heap))
heap_add_or_replace(triplet_heap,((1,2),0.1,(2,3)))
print("the new heap is: "+str(triplet_heap))
heap_add_or_replace(triplet_heap,((1,2),0.05,(2,0)))
print("the new heap is: "+str(triplet_heap))
heap_add_or_replace(triplet_heap,((4,6),2,(2,3)))
print("the new heap is: "+str(triplet_heap))
heap_add_or_replace(triplet_heap,((1,2),0.01,(2,0)))
print("the new heap is: "+str(triplet_heap))
heap_add_or_replace(triplet_heap,((4,6),9,(2,3)))
print("the new heap is: "+str(triplet_heap))
和预期结果:
the new heap is: [((2, 3), 0.9, (1, 0))]
the new heap is: [((7, 2), 0.3, (2, 2)), ((2, 3), 0.9, (1, 0))]
the new heap is: [((7, 2), 0.3, (2, 2)), ((2, 3), 0.9, (1, 0)), ((3, 2), 1, (2, 2))]
the new heap is: [((7, 2), 0.3, (2, 2)), ((2, 3), 0.9, (1, 0)), ((3, 2), 1, (2, 2))]
the new heap is: [((7, 2), 0.2, (2, 3)), ((2, 3), 0.9, (1, 0)), ((3, 2), 1, (2, 2))]
the new heap is: [((7, 2), 0.2, (2, 3)), ((1, 2), 0.3, (2, 3)), ((2, 3), 0.9, (1, 0)), ((3, 2), 1, (2, 2))]
the new heap is: [((1, 2), 0.1, (2, 3)), ((7, 2), 0.2, (2, 3)), ((2, 3), 0.9, (1, 0)), ((3, 2), 1, (2, 2))]
the new heap is: [((1, 2), 0.05, (2, 0)), ((7, 2), 0.2, (2, 3)), ((2, 3), 0.9, (1, 0)), ((3, 2), 1, (2, 2))]
the new heap is: [((1, 2), 0.05, (2, 0)), ((7, 2), 0.2, (2, 3)), ((2, 3), 0.9, (1, 0)), ((3, 2), 1, (2, 2)), ((4, 6), 2, (2, 3))]
the new heap is: [((1, 2), 0.01, (2, 0)), ((7, 2), 0.2, (2, 3)), ((2, 3), 0.9, (1, 0)), ((3, 2), 1, (2, 2)), ((4, 6), 2, (2, 3))]
the new heap is: [((1, 2), 0.01, (2, 0)), ((7, 2), 0.2, (2, 3)), ((2, 3), 0.9, (1, 0)), ((3, 2), 1, (2, 2)), ((4, 6), 2, (2, 3))]