add tests for tree_sort (#10015)

* add tests for tree_sort

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update tree_sort.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Gabrielly de S. Pinto Dantas 2023-10-15 21:44:10 -03:00 committed by GitHub
parent bb8f194957
commit 1a26d76c60
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,53 +1,70 @@
""" """
Tree_sort algorithm. Tree_sort algorithm.
Build a BST and in order traverse. 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 dataclasses import dataclass
@dataclass
class Node: class Node:
# BST data structure val: int
def __init__(self, val): left: Node | None = None
self.val = val right: Node | None = None
self.left = None
self.right = None
def insert(self, val): def __iter__(self) -> Iterator[int]:
if self.val: if self.left:
if val < self.val: yield from self.left
if self.left is None: yield self.val
self.left = Node(val) if self.right:
else: yield from self.right
self.left.insert(val)
elif val > self.val: def __len__(self) -> int:
if self.right is None: return sum(1 for _ in self)
self.right = Node(val)
else: def insert(self, val: int) -> None:
self.right.insert(val) if val < self.val:
else: if self.left is None:
self.val = val self.left = Node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = Node(val)
else:
self.right.insert(val)
def inorder(root, res): def tree_sort(arr: list[int]) -> tuple[int, ...]:
# Recursive traversal """
if root: >>> tree_sort([])
inorder(root.left, res) ()
res.append(root.val) >>> tree_sort((1,))
inorder(root.right, res) (1,)
>>> tree_sort((1, 2))
(1, 2)
def tree_sort(arr): >>> tree_sort([5, 2, 7])
# Build BST (2, 5, 7)
>>> tree_sort((5, -4, 9, 2, 7))
(-4, 2, 5, 7, 9)
>>> 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
"""
if len(arr) == 0: if len(arr) == 0:
return arr return tuple(arr)
root = Node(arr[0]) root = Node(arr[0])
for i in range(1, len(arr)): for item in arr[1:]:
root.insert(arr[i]) root.insert(item)
# Traverse BST in order. return tuple(root)
res = []
inorder(root, res)
return res
if __name__ == "__main__": if __name__ == "__main__":
print(tree_sort([10, 1, 3, 2, 9, 14, 13])) import doctest
doctest.testmod()
print(f"{tree_sort([5, 6, 1, -1, 4, 37, -3, 7]) = }")