Fix/tree sort iterable type hint#14701
Open
DrishtiTripathi2230 wants to merge 2 commits into
Open
Conversation
2818754 to
1395b59
Compare
d3dd32b to
161a738
Compare
for more information, see https://pre-commit.ci
diusazzad
suggested changes
May 24, 2026
diusazzad
left a comment
There was a problem hiding this comment.
provided a fix for iterable type hint
|
|
||
|
|
||
| def tree_sort(arr: list[int]) -> tuple[int, ...]: | ||
| def tree_sort(arr: Iterable[int]) -> tuple[int, ...]: |
There was a problem hiding this comment.
Hey @DrishtiTripathi2230! Thanks for taking the time to improve the type hints! 🚀
Changing the type hint to Iterable[int] is a great idea conceptually. However, it introduces a subtle bug. Since Iterable includes generators, passing a generator will cause the code to crash because:
len(arr)will raise aTypeError(generators have nolen()).arr[0]andarr[1:]will also raise aTypeError(generators are not subscriptable).
To fix this and fully support any Iterable, we can convert the iterable into an iterator using iter(). Here is a suggested fix for the logic inside the function:
def tree_sort(arr: Iterable[int]) -> tuple[int, ...]:
# ... docstrings ...
iterator = iter(arr)
try:
first = next(iterator)
except StopIteration:
return ()
root = Node(first)
for item in iterator:
root.insert(item)
return tuple(root)
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Describe your change:
Improve type hint for
tree_sortto accept anyIterable[int]instead of onlylist[int], and enable the previously commented-out range doctest.Checklist: