added BST, but remove not working

This commit is contained in:
2024-02-15 04:40:13 +01:00
parent 4c5d27e8d1
commit c7c1f3ea98
4 changed files with 113 additions and 61 deletions

View File

@ -1,24 +1,51 @@
from search_trees import BinarySearchTree
from typing import Iterator, Optional
from search_trees import BinarySearchTree, insert, remove, exists
from trees import Node
from random import randint as random
MAX= 1000
def traverse[T](tree: Optional[Node[T]]) -> Iterator[T]:
match tree:
case Node(value, left, right):
yield from traverse(left)
yield value
yield from traverse(right)
case _:
return
MAX = 100
MIN = 0
LENGTH = 100
NUMS = {random(MIN, MAX) for _ in range(0, LENGTH)}
NUMS_FILTER = {random(MIN, MAX) for _ in range(0, LENGTH // 4)}
def test_insert():
nums = [random(MIN, MAX) for _ in range(0, LENGTH)]
bst = BinarySearchTree()
for num in nums:
bst.insert(num)
assert list(iter(bst)) == sorted(nums)
bst: BinarySearchTree = None
for num in NUMS:
bst = insert(bst, num)
assert list(traverse(bst)) == sorted(NUMS)
def test_remove():
nums = {random(MIN, MAX) for _ in range(0, LENGTH)}
fil = {random(MIN, MAX) for _ in range(0, LENGTH // 4)}
bst = BinarySearchTree()
for num in nums:
bst.insert(num)
for num in fil:
bst.remove(num)
assert list(iter(bst)) == sorted(filter(lambda x: x not in fil, nums))
bst: BinarySearchTree = None
for num in NUMS:
bst = insert(bst, num)
assert list(traverse(bst)) == sorted(NUMS)
for num in NUMS_FILTER:
remove(bst, num)
assert list(traverse(bst)) == sorted(filter(lambda x: x not in NUMS_FILTER, NUMS))
def test_exists():
bst: BinarySearchTree = None
for num in NUMS:
bst = insert(bst, num)
for num in NUMS_FILTER:
remove(bst, num)
assert all(map(lambda x: exists(bst, x),
filter(lambda x: x not in NUMS_FILTER, NUMS)))
assert all(map(lambda x: not exists(bst, x), NUMS_FILTER))