Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7081709
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T06:57:17+00:00 2026-05-28T06:57:17+00:00

I am trying to build a heap with a custom sort predicate. Since the

  • 0

I am trying to build a heap with a custom sort predicate. Since the values going into it are of "user-defined" type, I cannot modify their built-in comparison predicate.

Is there a way to do something like:

h = heapq.heapify([...], key=my_lt_pred)
h = heapq.heappush(h, key=my_lt_pred)

Or even better, I could wrap the heapq functions in my own container so I don’t need to keep passing the predicate.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T06:57:18+00:00Added an answer on May 28, 2026 at 6:57 am

    According to the heapq documentation, the way to customize the heap order is to have each element on the heap to be a tuple, with the first tuple element being one that accepts normal Python comparisons.

    The functions in the heapq module are a bit cumbersome (since they are not object-oriented), and always require our heap object (a heapified list) to be explicitly passed as the first parameter. We can kill two birds with one stone by creating a very simple wrapper class that will allow us to specify a key function, and present the heap as an object.

    The class below keeps an internal list, where each element is a tuple, the first member of which is a key, calculated at element insertion time using the key parameter, passed at Heap instantiation:

    # -*- coding: utf-8 -*-
    import heapq
    
    class MyHeap(object):
        def __init__(self, initial=None, key=lambda x:x):
            self.key = key
            self.index = 0
            if initial:
                self._data = [(key(item), i, item) for i, item in enumerate(initial)]
                self.index = len(self._data)
                heapq.heapify(self._data)
            else:
                self._data = []
    
        def push(self, item):
            heapq.heappush(self._data, (self.key(item), self.index, item))
            self.index += 1
    
        def pop(self):
            return heapq.heappop(self._data)[2]
    

    (The extra self.index part is to avoid clashes when the evaluated key value is a draw and the stored value is not directly comparable – otherwise heapq could fail with TypeError)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to build a function in C/C++ to sort an array and
Trying to build my own user control: <%@ Control Language=C# AutoEventWireup=true CodeFile=TabMenu.ascx.cs Inherits=TabMenu %>
I'm trying to build a home-made min-heap with template class so I can work
I'm trying build an sort of property set in ksh. Thought the easiest way
Trying to build a linq query based on parameters a user selects (reporting) but
im trying to build an application like a book, with so many custom views
I'm trying build a method which returns the shortest path from one node to
Trying to build a GUI application in Java/Swing. I'm mainly used to painting GUIs
Trying to build sslsniff on a RHEL 5.2 system here. When compiling sslsniff on
I trying to build and compile my xcodeproj in command line and it is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.