Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active April 5, 2017 02:16
Show Gist options
  • Save pokk/a13e6555a15647d154635d0250da412a to your computer and use it in GitHub Desktop.
Save pokk/a13e6555a15647d154635d0250da412a to your computer and use it in GitHub Desktop.
effective heapq

Introduction

If you want to use the min() or max() function in python. There is that an alternative way of the speedy method is headq.

benifits

The time complexity for finding a max value and a min value is O(logn).
Time complexity of min() and max() are O(n).

Talk is cheap. Show me the code.

import heapq

h = []

heapq.heappush(h, (0, 10))
heapq.heappush(h, (4, 5))
heapq.heappush(h, (3, 2))
heapq.heappush(h, (3, 5))
heapq.heappush(h, (1, 5))

heapq.heappop(h)
# >>> (0, 10)

# You could change to max heap and get maximum number from it.
heapq._heapify_max(h)

heapq.heappop(h)
# >>> (4, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment