DEV Community

Writing a Minimum-Heap in Python3

darkmage on March 29, 2019

Before I get started, if you need some background on what a heap is: https://en.wikipedia.org/wiki/Heap_(data_structure) This discussion is abo...
Collapse
 
zacharypatten profile image
Zachary Patten

You might want to look at my code. It is in C#, but I have a generic heap, and all you need to make a heap is a compare function. You don't need two values when you add to a heap. You can have multiple heaps of the same type but they can use different priority algorithms based on the delegate you pass in on construction.
github.com/ZacharyPatten/Towel

Collapse
 
therealdarkmage profile image
darkmage

This was a student of mine's homework project. His professor's specifications required the Heap to store Node objects with key-values on them. I understand that you can do this many different ways, but thank you for the clarification. I like the idea of initializing with a different delegate to indicate algorithm changes :)

Collapse
 
zacharypatten profile image
Zachary Patten

If you have to store keys and values, all you do is (in C# using my example) this:

Heap<(KeyType, ValueType)>

So there should only ever be one generic type, even if you need to store multiple values, you just pass in a type with multiple values.

Just wanted to clarify that. Let me know if that doesn't make sense and I will gladly elaborate.

But yeah. Hope the student had fun figuring out the algorithms of a heap. :)

Thread Thread
 
therealdarkmage profile image
darkmage

Yeah, your template looks a lot like the templating stuff I'd use in C++ and Java (I don't know C# but I understand it is similar enough).

We both had fun working through the methods :D It is definitely good practice.