Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions sorts/tree_sort.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
"""
Tree_sort algorithm.

Build a Binary Search Tree and then iterate thru it to get a sorted list.
"""

from __future__ import annotations

from collections.abc import Iterator
from collections.abc import Iterable, Iterator
from dataclasses import dataclass


Expand Down Expand Up @@ -39,7 +38,7 @@ def insert(self, val: int) -> None:
self.right.insert(val)


def tree_sort(arr: list[int]) -> tuple[int, ...]:
def tree_sort(arr: Iterable[int]) -> tuple[int, ...]:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. len(arr) will raise a TypeError (generators have no len()).
  2. arr[0] and arr[1:] will also raise a TypeError (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)

"""
>>> tree_sort([])
()
Expand All @@ -54,8 +53,8 @@ def tree_sort(arr: list[int]) -> tuple[int, ...]:
>>> tree_sort([5, 6, 1, -1, 4, 37, 2, 7])
(-1, 1, 2, 4, 5, 6, 7, 37)

# >>> tree_sort(range(10, -10, -1)) == tuple(sorted(range(10, -10, -1)))
# True
>>> tree_sort(range(10, -10, -1)) == tuple(sorted(range(10, -10, -1)))
True
"""
if len(arr) == 0:
return tuple(arr)
Expand Down