Add randomized heap. - #3241
Add randomized heap.#3241
Conversation
| """ | ||
| self._root = None | ||
|
|
||
| def to_sorted_list(self) -> List[T]: |
| """ | ||
| result = [] | ||
| while self: | ||
| result.append(self.pop()) |
There was a problem hiding this comment.
It would surprise me as a user of this class that requesting a list would remove all data from the heap.
There was a problem hiding this comment.
Do you suggest to add all the items back to the heap at the end of the method?
There was a problem hiding this comment.
I would suggest that you replace .to_sorted_list() with .__iter__() and that method should not use .pop() but should just yield values as it walks thru the heap.
Please search this repo for instances of __intr__() to see how this is done.
There was a problem hiding this comment.
I mean I know how __iter__ works in python. But we can't iterate over heap to get sorted values. In BST we know where is the next element but in the heap, we can only pop the smallest. We can't get the second element.
I can do it like this since __iter__ can work in time larger than O(1). And we don't need the structure to be thread-safe, we can modify it. So poping and pushing back works.
WDYT?
def __iter__(self) -> Iterator[T]:
"""
Returns sorted list containing all the values in the heap.
>>> sh = RandomizedHeap([3, 1, 3, 7])
>>> list(sh)
[1, 3, 3, 7]
"""
result = []
while self:
result.append(self.pop())
# Pushing items back to the heap not to clear it.
for item in result:
self.insert(item)
return iter(result)
There was a problem hiding this comment.
Good enough for now. Thanks for doing this!
| structure. | ||
| Wiki: https://en.wikipedia.org/wiki/Randomized_meldable_heap | ||
|
|
||
| >>> RandomizedHeap([2, 3, 1, 5, 1, 7]).to_sorted_list() |
There was a problem hiding this comment.
Should pass if .__iter__() is properly implemented.

Add randomized heap data structure
A data structure that allows inserting a new value and to pop the smallest values. Both operations take O(logN) time where N is the size of the structure.
Wiki: https://en.wikipedia.org/wiki/Randomized_meldable_heap
Checklist:
Fixes: #{$ISSUE_NO}.