Puzzle 4 A Task to Do

Python Brain Teasers — by Miki Tebeka (13 / 40)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 When in Kraków | TOC | Send It to the Printer 👉

tasks.py

​1: ​from​ ​heapq​ ​import​ heappush, heappop
​-
​- tasks = []
​- heappush(tasks, (30, ​'work out'​))
​5: heappush(tasks, (10, ​'wake up'​))
​- heappush(tasks, (20, 0xCAFFE))
​- heappush(tasks, (20, ​'feed cat'​))
​- heappush(tasks, (40, ​'write book'​))
​-
​10: ​while​ tasks:
​- _, payload = heappop(tasks)
​- ​print​(payload)

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will raise a TypeError exception.

images/hline.png

The built-in heapq module implements min-heap over lists.

It’s common to use a heap for a priority queue. Pushing and deleting from the heap are log(N) operations, and the first item in the heap (e.g., tasks[0]) is always the smallest.

To compare items in the heap, heapq uses the comparison defined in the object’s type (using the < operator, which maps to the specific type’s __lt__ special…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.