最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How does heapq affect list that is not heapified? - Stack Overflow

programmeradmin2浏览0评论

This is a curious exercise to understand the inner workings of heapq and why heapify is done.

Experiment 1

from heapq import heappush, heappop

data = [3,2,1]
# heappush(data,4)
heappop(data),heappop(data),heappop(data)#,heappop(data)

Output: (3, 1, 2).

What did heappop do to the list to make 1 and 2 swap positions? Which of the first two heappops did this?

Experiment 2 (pushing 1 element + popping 1 more)

data = [3,2,1]
heappush(data,4)
heappop(data),heappop(data),heappop(data),heappop(data)

Output: (3, 1, 2, 4)

Experiment 3 (change pushed element from 4 to 0)

data = [3,2,1]
heappush(data,0)
heappop(data),heappop(data),heappop(data),heappop(data)

Output:: (0, 1, 2, 3)

Why when pushing 4, the output seems similar to experiment 1 (Please compare mechanics of experiment 1 and experiment 2), but when pushing 0, the other 3 elements also changed positions?

It looks like pushing 0 instead of 4 turned the list into a real heap?

P.s I know heapify(data) can turn experiment 3 output to (1, 2, 3, 4), making it work normally is not the point of the question.

发布评论

评论列表(0)

  1. 暂无评论