Puzzle 4 A Task to Do
Python Brain Teasers — by Miki Tebeka (13 / 40)
👈 When in Kraków | TOC | Send It to the Printer 👉
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.
This code will raise a TypeError exception.
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…