-
-
Notifications
You must be signed in to change notification settings - Fork 49.6k
Add median in a stream using optimised heap-based approach #14004
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Bharatgwl
wants to merge
5
commits into
TheAlgorithms:master
Choose a base branch
from
Bharatgwl:add_heap_median_stream
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b29283c
Add median in a stream using heap-based approach
Bharatgwl 11162ae
Add reference link for running median algorithm
Bharatgwl 54f306d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 399d6d7
Use built-in list type hints for Python 3.9+
Bharatgwl 77b882d
Add median in a stream using heap-based approach with doctests
Bharatgwl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| """ | ||
| Median in a stream using a heap-based approach. | ||
|
|
||
| Reference: | ||
| https://en.wikipedia.org/wiki/Median#Running_median | ||
| """ | ||
|
|
||
| import heapq | ||
|
|
||
|
|
||
| def signum(a: int, b: int) -> int: | ||
| """ | ||
| Return 1 if a > b, -1 if a < b, 0 if equal. | ||
| """ | ||
| if a > b: | ||
| return 1 | ||
| if a < b: | ||
| return -1 | ||
| return 0 | ||
|
|
||
|
|
||
| def call_median( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file |
||
| element: int, | ||
| max_heap: list[int], | ||
| min_heap: list[int], | ||
| median: int, | ||
| ) -> int: | ||
| """ | ||
| Update heaps and median based on the new element. | ||
|
|
||
| Args: | ||
| element (int): new element in stream | ||
| max_heap (list[int]): max heap (as negative numbers) | ||
| min_heap (list[int]): min heap | ||
| median (int): current median | ||
|
|
||
| Returns: | ||
| int: updated median | ||
| """ | ||
| size_diff = signum(len(max_heap), len(min_heap)) | ||
|
|
||
| if size_diff == 0: | ||
| if element > median: | ||
| heapq.heappush(min_heap, element) | ||
| median = min_heap[0] | ||
| else: | ||
| heapq.heappush(max_heap, -element) | ||
| median = -max_heap[0] | ||
| elif size_diff == 1: | ||
| if element > median: | ||
| heapq.heappush(min_heap, element) | ||
| else: | ||
| heapq.heappush(min_heap, -heapq.heappushpop(max_heap, -element)) | ||
| median = (-max_heap[0] + min_heap[0]) // 2 | ||
| else: # size_diff == -1 | ||
| if element > median: | ||
| heapq.heappush(max_heap, -heapq.heappushpop(min_heap, element)) | ||
| else: | ||
| heapq.heappush(max_heap, -element) | ||
| median = (-max_heap[0] + min_heap[0]) // 2 | ||
|
|
||
| return median | ||
|
|
||
|
|
||
| def median_in_a_stream(arr: list[int]) -> list[int]: | ||
| """ | ||
| Return the median after each new element in the stream. | ||
|
|
||
| Args: | ||
| arr (list[int]): list of integers | ||
|
|
||
| Returns: | ||
| list[int]: running medians | ||
|
|
||
| >>> median_in_a_stream([20, 14, 13, 16, 17]) | ||
| [20, 17, 14, 15, 16] | ||
| >>> median_in_a_stream([5, 15, 1, 3]) | ||
| [5, 10, 5, 4] | ||
| >>> median_in_a_stream([]) | ||
| Traceback (most recent call last): | ||
| ... | ||
| ValueError: Input list must not be empty | ||
| """ | ||
| if not arr: | ||
| raise ValueError("Input list must not be empty") | ||
|
|
||
| max_heap: list[int] = [] # left side (as negative numbers) | ||
| min_heap: list[int] = [] # right side | ||
| median = arr[0] | ||
| max_heap.append(-arr[0]) | ||
| medians: list[int] = [median] | ||
|
|
||
| for element in arr[1:]: | ||
| median = call_median(element, max_heap, min_heap, median) | ||
| medians.append(median) | ||
|
|
||
| return medians | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| n = int(input("Enter number of elements: ").strip()) | ||
| arr = [int(input().strip()) for _ in range(n)] | ||
| result = median_in_a_stream(arr) | ||
| print("Running medians:", result) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As there is no test file in this pull request nor any test function or class in the file
data_structures/heap/median_in_a_stream.py, please provide doctest for the functionsignumPlease provide descriptive name for the parameter:
aPlease provide descriptive name for the parameter:
b