You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.2 KiB
Python
48 lines
1.2 KiB
Python
3 years ago
|
from treesort import TreeNode
|
||
|
from visualizer import visualize
|
||
|
from random import shuffle
|
||
|
import os.path
|
||
|
|
||
|
basepath = os.path.dirname(os.path.abspath(__file__))
|
||
|
|
||
|
# Alternative sorting function that has a comparator
|
||
|
def insert (root, value, key = lambda value: value):
|
||
|
if not root:
|
||
|
root = TreeNode()
|
||
|
root.value = value
|
||
|
else:
|
||
|
if value == root.value:
|
||
|
root.value = value
|
||
|
else:
|
||
|
if key(value) < key(root.value):
|
||
|
root.left = insert(root.left, value, key)
|
||
|
else:
|
||
|
root.right = insert(root.right, value, key)
|
||
|
return root
|
||
|
|
||
|
# Alternative make tree that allows for a callback
|
||
|
# which returns the sorting value.
|
||
|
# By default the sort value is the same as the value
|
||
|
def make_tree (values, key = lambda word: word):
|
||
|
tree = None
|
||
|
|
||
|
for value in values:
|
||
|
tree = insert(tree, value, key)
|
||
|
|
||
|
return tree
|
||
|
|
||
|
def clean (word):
|
||
|
return word.lower().strip(' .,!?-"()[]‘’“”')
|
||
|
|
||
|
def not_empty (word):
|
||
|
return (word)
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
with open(os.path.join(basepath, 'text-to-sort.txt'), 'r') as h:
|
||
|
text = h.read()
|
||
|
words = text.split(' ')
|
||
|
cleaned_words = list(filter(not_empty, map(clean, words)))
|
||
|
|
||
|
shuffle(cleaned_words)
|
||
|
|
||
|
visualize(make_tree(cleaned_words), 'text-tree-random')
|