堆排序 python

堆中某个节点的值总是不大于或不小于其父节点的值
堆总是一棵完全二叉树

 

 


# nums = [[2], [3], [5], [1], [54], [23], [132]]
# heap = []
# for num in nums:
# heapq.heappush(heap, num) # 加入堆

# print(heap[0]) # 如果只是想获取最小值而不是弹出,使用heap[0]
# print([heapq.heappop(heap) for _ in range(len(nums))]) # 堆排序结果
# out: [1, 2, 3, 5, 23, 54, 132]
# -------merge--------------------
# num1 = [32, 3, 5, 34, 54, 23, 132]
# num2 = [23, 2, 12, 656, 324, 23, 54]
# num1 = sorted(num1)
# num2 = sorted(num2)
#
# res = heapq.merge(num1, num2)
# print(list(res))
# ------------删除最小的元素,添加一个新元素--------
# import heapq
#
# nums = [1, 2, 4, 5, 3]
# heapq.heapify(nums)
#
# heapq.heapreplace(nums, 23)
#
# print([heapq.heappop(nums) for _ in range(len(nums))])
# out: [2, 3, 4, 5, 23]

# 快速排序
print(heapq.nlargest(10, dict(Counter(score_A)+Counter(score_B)).items(), key=lambda x: x[1]))
print(heapq.nsmallest(10, dict(Counter(score_A)+Counter(score_B)).items(), key=lambda x: x[1]))

posted on 2020-04-09 17:43  nnnnnnnnnnnnnnnn  阅读(168)  评论(0)    收藏  举报

导航