示例#1
0
    def clear_tree_handler(self, args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        self.rbtree = RBTree()
        print("The tree has been cleared!")
        return False
示例#2
0
def RBT():
    rbtTree = RBTree()
    with open(fileName) as f:
        for line in f:
            node = (line.lower())  #this line makes every word a lower case
            rbtTree.insert(node)

    return rbtTree
示例#3
0
def main():
    print("RB Trees!")
    test_tree_1 = RBTree(25, 16, 32, 7, 17, 27, 37)
    test_tree_2 = RBTree(25)
    print(test_tree_2)
    print(test_tree_1)

    int_mod = InteractiveModule()
    int_mod.run()
def RBT(fileName):
    rbtTree = RBTree()
    with open(fileName) as f:
        for line in f:
            if "\n" in line:
                line = line.replace("\n", "")
            node = (line.lower())  #this line makes every word a lower case
            rbtTree.insert(node)

    return rbtTree
示例#5
0
def create_rb(words):
        # create an rb tree
        rb_tree = RBTree()
        # read the file
        file = open(words, "r")
        line = file.readline()
        # while loop to read all lines in file
        while line:
            # each word is added to the tree
            new_word = Node(line.rstrip().lower())
            rb_tree.insert(new_word)
            line = file.readline()
        # return the tree
        return rb_tree
示例#6
0
 def get_stat_arithmetic_progression(n, step):
     count = 0
     counts = []
     iterations = []
     for i in range(n):
         rb = RBTree()
         count = count + step
         for i in range(0, count):
             rb.insert(randint(0, 1000))
         counts.append(count)
         iterations.append(rb.iterations_insert)
     data = dict(length=counts, iterations=iterations)
     df = pandas.DataFrame(data)
     df.to_csv(r'iterations_arith.csv', sep=';', index=False)
     print("Complete!")
示例#7
0
 def test_tree_insert_left_node(self):
     rb_tree = RBTree()
     rb_node = RBTreeNode(9)
     rb_node_left = RBTreeNode(6)
     sol = Solution()
     sol.RBInsert(rb_tree, rb_node)
     sol.RBInsert(rb_tree, rb_node_left)
     self.assertEqual(rb_tree.root.left.key, rb_node_left.key)
示例#8
0
 def test_tree_insert_right_node(self):
     rb_tree = RBTree()
     rb_node = RBTreeNode(9)
     rb_node_right = RBTreeNode(10)
     sol = Solution()
     sol.RBInsert(rb_tree, rb_node)
     sol.RBInsert(rb_tree, rb_node_right)
     self.assertEqual(rb_tree.root.right.key, rb_node_right.key)
示例#9
0
 def __init__(self):
     print("Interactive mode on!")
     self.rbtree = RBTree()
     self.user_input_handlers_map = {
         "ADD": self.add_handler,
         "REMOVE": self.remove_handler,
         "CLEAR_TREE": self.clear_tree_handler,
         "CONTAINS": self.contains_handler,
         "SIZE": self.size_handler,
         "PRINT": self.print_handler,
         "TOGGLE_NULL_DISPLAY": self.toggle_null_display_handler,
         "TOGGLE_COLOUR_DISPLAY": self.toggle_colour_display_handler,
         "PREORDER": self.preorder_handler,
         "INORDER": self.inorder_handler,
         "POSTORDER": self.postorder_handler,
         "BFS": self.bfs_handler,
         "HELP": InteractiveModule.help_handler,
         "QUIT": InteractiveModule.quit_handler
     }
示例#10
0
文件: Lab3B.py 项目: liizzee18/lab3-1
def read_file_rb(filename):
    """
  Creates a red black binary search tree from a file of words
  
  Args:
    filename: The name of the file to be parsed
  
  Returns:
    tree: A red black binary search tree

  """
    reader = open(filename, "r")
    lines = reader.readlines()
    tree = RBTree()
    for line in lines:
        # Removes newline character from line
        if "\n" in line:
            line = line.replace("\n", "")
        tree.insert(line)
    return tree
示例#11
0
def get_sort(arr):
    rb = RBTree()
    for e in arr:
        rb.insert(e)
    rb.getsorted(rb.root)
    result = rb.result
    return result
示例#12
0
    def test_tree_insert(self):
        rb_tree = RBTree()
        rb_node = RBTreeNode(9)
        rb_node_left = RBTreeNode(4)
        rb_node_right = RBTreeNode(20)
        sol = Solution()
        sol.RBInsert(rb_tree, rb_node)
        sol.RBInsert(rb_tree, rb_node_left)
        sol.RBInsert(rb_tree, rb_node_right)

        rb_node_insert = RBTreeNode(3)
        sol.RBInsert(rb_tree, rb_node_insert)
        self.assertEqual(rb_tree.root.left.left.key, rb_node_insert.key)
        self.assertEqual(rb_tree.root.left.left.color, 'red')

        rb_node_insert = RBTreeNode(5)
        sol.RBInsert(rb_tree, rb_node_insert)
        self.assertEqual(rb_tree.root.left.right.key, rb_node_insert.key)
        self.assertEqual(rb_tree.root.left.right.color, 'red')
示例#13
0
    def test_tree_delete(self):
        rb_tree = RBTree()
        sol = Solution()
        rb_node_insert = RBTreeNode(9)
        sol.RBInsert(rb_tree, rb_node_insert)
        rb_node_insert_del = RBTreeNode(4)
        sol.RBInsert(rb_tree, rb_node_insert_del)
        rb_node_insert = RBTreeNode(20)
        sol.RBInsert(rb_tree, rb_node_insert)
        rb_node_insert = RBTreeNode(3)
        sol.RBInsert(rb_tree, rb_node_insert)
        rb_node_insert = RBTreeNode(5)
        sol.RBInsert(rb_tree, rb_node_insert)

        sol.RBDelete(rb_tree, rb_node_insert_del)

        self.assertEqual(rb_tree.root.key, 9)
        self.assertEqual(rb_tree.root.color, 'black')
        self.assertEqual(rb_tree.root.left.key, 5)
        self.assertEqual(rb_tree.root.left.color, 'black')
        self.assertEqual(rb_tree.root.left.left.key, 3)
        self.assertEqual(rb_tree.root.left.left.color, 'red')
        self.assertEqual(rb_tree.root.right.key, 20)
        self.assertEqual(rb_tree.root.right.color, 'black')
示例#14
0
    def test_two(self, capsys):
        """
        Scenario 2. This test tests some way-side class methods and fields.

        :param capsys: Used for capturing and testing stdout
        :return:  nothing, this is a test method
        """

        test_tree = RBTree(500, 225, 777, 639, 1231, 566, 25, 1, 5, 7, 6, 778,
                           821, 325, 267, 298, 340, 344, 404)
        test_tree.display_null_leaves = True

        # Time to add the duplicates
        test_tree.add_node(7)
        test_tree.add_node(1231)

        test_tree.add_node(500)
        test_tree.add_node(778)

        test_tree.add_node(1231)
        test_tree.add_node(566)
        test_tree.add_node(340)
        test_tree.add_node(500)
        test_tree.add_node(1231)
        test_tree.add_node(639)
        test_tree.add_node(5)
        test_tree.add_node(340)

        test_tree.add_node(6)
        test_tree.add_node(566)
        test_tree.add_node(566)
        test_tree.add_node(566)

        test_tree.add_node(340)
        test_tree.add_node(1231)

        test_tree.add_node(340)
        test_tree.add_node(566)
        test_tree.add_node(344)
        test_tree.add_node(6)
        test_tree.add_node(1231)

        # Assert structure
        test_tree.bfs_traversal()
        out, err = capsys.readouterr()
        assert out == "(B)500 \n(R)25 (B)777 \n(B)5 (B)267 (B)639 (B)821 \n" \
                      "(B)1 (B)7 (B)225 (R)325 (R)566 (B)NULL (R)778 (R)1231 \n(B)NULL (B)NULL (R)6 (B)NULL (B)NULL (B)NULL " \
                      "(B)298 (B)344 (B)NULL (B)NULL (B)NULL (B)NULL (B)NULL (B)NULL \n" \
                      "(B)NULL (B)NULL (B)NULL (B)NULL (R)340 (R)404 \n(B)NULL (B)NULL (B)NULL (B)NULL \n"

        # Assert duplicates counter
        out = test_tree.get_counter(500)
        assert out == 3

        out = test_tree.get_counter(225)
        assert out == 1

        out = test_tree.get_counter(777)
        assert out == 1

        out = test_tree.get_counter(639)
        assert out == 2

        out = test_tree.get_counter(1231)
        assert out == 6

        out = test_tree.get_counter(566)
        assert out == 6

        out = test_tree.get_counter(25)
        assert out == 1

        out = test_tree.get_counter(1)
        assert out == 1

        out = test_tree.get_counter(5)
        assert out == 2

        out = test_tree.get_counter(7)
        assert out == 2

        out = test_tree.get_counter(6)
        assert out == 3

        out = test_tree.get_counter(778)
        assert out == 2

        out = test_tree.get_counter(821)
        assert out == 1

        out = test_tree.get_counter(325)
        assert out == 1

        out = test_tree.get_counter(267)
        assert out == 1

        out = test_tree.get_counter(298)
        assert out == 1

        out = test_tree.get_counter(340)
        assert out == 5

        out = test_tree.get_counter(344)
        assert out == 2

        out = test_tree.get_counter(404)
        assert out == 1

        # Assert some nodes not inside!

        out = test_tree.get_counter(-56)
        assert out == 0

        out = test_tree.get_counter(0)
        assert out == 0

        out = test_tree.get_counter(14)
        assert out == 0

        out = test_tree.get_counter(1000000)
        assert out == 0

        out = test_tree.get_counter(640)
        assert out == 0

        out = test_tree.get_counter(638)
        assert out == 0

        out = test_tree.get_counter(299)
        assert out == 0

        # Assert find node
        res = test_tree.find_node(500)
        assert res is not None
        assert res.getElement == 500

        res = test_tree.find_node(777)
        assert res is not None
        assert res.getElement == 777

        res = test_tree.find_node(325)
        assert res is not None
        assert res.getElement == 325

        res = test_tree.find_node(7)
        assert res is not None
        assert res.getElement == 7

        res = test_tree.find_node(404)
        assert res is not None
        assert res.getElement == 404

        # Time for some nodes not inside
        res = test_tree.find_node(-64)
        assert res is None

        res = test_tree.find_node(-64)
        assert res is None

        res = test_tree.find_node(341)
        assert res is None

        res = test_tree.find_node(345)
        assert res is None

        res = test_tree.find_node(9999)
        assert res is None

        res = test_tree.find_node(0)
        assert res is None

        # Inorder, preorder and postorder
        test_tree.inorder_traversal()
        out, err = capsys.readouterr()
        assert out == "(B)1 (B)5 (R)6 (B)7 (R)25 (B)225 (B)267 (B)298 (R)325 (R)340 (B)344 (R)404 (B)500 (R)566 " \
                      "(B)639 (B)777 (R)778 (B)821 (R)1231 \n"

        test_tree.preorder_traversal()
        out, err = capsys.readouterr()
        assert out == "(B)500 (R)25 (B)5 (B)1 (B)7 (R)6 (B)267 (B)225 (R)325 (B)298 (B)344 (R)340 (R)404 " \
                      "(B)777 (B)639 (R)566 (B)821 (R)778 (R)1231 \n"

        test_tree.postorder_traversal()
        out, err = capsys.readouterr()
        assert out == "(B)1 (R)6 (B)7 (B)5 (B)225 (B)298 (R)340 (R)404 (B)344 (R)325 (B)267 (R)25 (R)566 " \
                      "(B)639 (R)778 (R)1231 (B)821 (B)777 (B)500 \n"

        # Non-null display bfs
        test_tree.display_null_leaves = False
        test_tree.bfs_traversal()
        out, err = capsys.readouterr()
        assert out == "(B)500 \n(R)25 (B)777 \n(B)5 (B)267 (B)639 (B)821 \n" \
                      "(B)1 (B)7 (B)225 (R)325 (R)566 (R)778 (R)1231 \n(R)6 (B)298 (B)344 \n(R)340 (R)404 \n\n"

        # Display null leaves bfs
        test_tree.display_null_leaves = True
        test_tree.bfs_traversal()
        out, err = capsys.readouterr()
        assert out == "(B)500 \n(R)25 (B)777 \n(B)5 (B)267 (B)639 (B)821 \n" \
                      "(B)1 (B)7 (B)225 (R)325 (R)566 (B)NULL (R)778 (R)1231 \n(B)NULL (B)NULL (R)6 (B)NULL (B)NULL " \
                      "(B)NULL (B)298 (B)344 (B)NULL (B)NULL (B)NULL (B)NULL (B)NULL (B)NULL \n" \
                      "(B)NULL (B)NULL (B)NULL (B)NULL (R)340 (R)404 \n" \
                      "(B)NULL (B)NULL (B)NULL (B)NULL \n"
示例#15
0
 def test_tree_insert_root(self):
     rb_tree = RBTree()
     rb_node = RBTreeNode(9)
     sol = Solution()
     sol.RBInsert(rb_tree, rb_node)
     self.assertEqual(rb_tree.root.key, rb_node.key)
示例#16
0
 def test_tree_init(self):
     nil = RBTreeNode(-1)
     rb_tree = RBTree()
     self.assertEqual(rb_tree.root.key, nil.key)
示例#17
0
def test_tree():
    return RBTree()
    print('Total words: ', len(words))
    print('Unique words: ', avl_tree.get_size())
    print('Contains word "they": ', avl_tree.contains('they'))
    ## 耗时1.23秒左右
    print('AVL Total time: {} seconds'.format(time() - start_time))

    avl_tree.remove('they')
    print(avl_tree.contains('they'))
    # avl_tree.setter('they', 100)
    # print(avl_tree.getter('they'))

    print('*' * 20)

    start_time = time()
    rb_tree = RBTree()
    for word in words:
        if rb_tree.contains(word):
            rb_tree.setter(word, rb_tree.getter(word) + 1)
        else:
            rb_tree.add(word, 1)

    print('Total words: ', len(words))
    print('Unique words: ', rb_tree.get_size())
    print('Contains word "they": ', rb_tree.contains('they'))
    ## 耗时1.23秒左右
    print('RBTree Total time: {} seconds'.format(time() - start_time))

    rb_tree.remove('they')
    print(rb_tree.contains('they'))
    rb_tree.setter('they', 100)
示例#19
0
    def test_print(self, capsys):
        """
        Testing print function

        :param capsys: Used for capturing and testing stdout
        :return:  nothing, this is a test method
        """
        test_tree = RBTree(500, 225, 777, 639, 1231, 566, 25, 1, 5, 7, 6, 778,
                           821, 325, 267, 298, 340, 344, 404)
        test_tree.display_null_leaves = True

        print(test_tree)
        out, err = capsys.readouterr()
        assert out == """└──(Black)500
    ├──(Black)777
    │   ├──(Black)821
    │   │   ├──(Red)1231
    │   │   │   ├──(Black)NULL
    │   │   │   └──(Black)NULL
    │   │   └──(Red)778
    │   │       ├──(Black)NULL
    │   │       └──(Black)NULL
    │   └──(Black)639
    │       ├──(Black)NULL
    │       └──(Red)566
    │           ├──(Black)NULL
    │           └──(Black)NULL
    └──(Red)25
        ├──(Black)267
        │   ├──(Red)325
        │   │   ├──(Black)344
        │   │   │   ├──(Red)404
        │   │   │   │   ├──(Black)NULL
        │   │   │   │   └──(Black)NULL
        │   │   │   └──(Red)340
        │   │   │       ├──(Black)NULL
        │   │   │       └──(Black)NULL
        │   │   └──(Black)298
        │   │       ├──(Black)NULL
        │   │       └──(Black)NULL
        │   └──(Black)225
        │       ├──(Black)NULL
        │       └──(Black)NULL
        └──(Black)5
            ├──(Black)7
            │   ├──(Black)NULL
            │   └──(Red)6
            │       ├──(Black)NULL
            │       └──(Black)NULL
            └──(Black)1
                ├──(Black)NULL
                └──(Black)NULL

"""

        test_tree = RBTree("0025", "0004", "0003", "0010", "0015", "0030",
                           "0035", "0045", "0037", "0038", "-22", "-1", "0000",
                           "0002", "0025", "0003", "-288", "-303", "0404",
                           "0676", "0474", "0003", "0003", "0025", "0025",
                           "0025", "0000", "-7", "-5", "0000", "-21", "-25",
                           "-37", "-23")
        test_tree.display_null_leaves = True

        print(test_tree)
        out, err = capsys.readouterr()
        assert out == """└──(Black)0015
示例#20
0
class InteractiveModule:
    __help_string = """
    Available commands are:
    ADD X
    REMOVE X
    CLEAR_TREE
    CONTAINS X
    SIZE
    PRINT
    TOGGLE_NULL_DISPLAY
    TOGGLE_COLOUR_DISPLAY
    PREORDER
    INORDER
    POSTORDER
    BFS
    HELP
    QUIT
    """

    __DELAY_SECONDS = 0.025  # 25 ms delay in order to prevent stdout and stderr mixing

    def __init__(self):
        print("Interactive mode on!")
        self.rbtree = RBTree()
        self.user_input_handlers_map = {
            "ADD": self.add_handler,
            "REMOVE": self.remove_handler,
            "CLEAR_TREE": self.clear_tree_handler,
            "CONTAINS": self.contains_handler,
            "SIZE": self.size_handler,
            "PRINT": self.print_handler,
            "TOGGLE_NULL_DISPLAY": self.toggle_null_display_handler,
            "TOGGLE_COLOUR_DISPLAY": self.toggle_colour_display_handler,
            "PREORDER": self.preorder_handler,
            "INORDER": self.inorder_handler,
            "POSTORDER": self.postorder_handler,
            "BFS": self.bfs_handler,
            "HELP": InteractiveModule.help_handler,
            "QUIT": InteractiveModule.quit_handler
        }

    def run(self):
        print("Welcome to RB Trees interactive mode!")
        print(InteractiveModule.__help_string)
        print("Please enter your query >", end="")
        while True:
            quit_bool = self.parse_input()
            if quit_bool:
                return
            else:
                sleep(InteractiveModule.__DELAY_SECONDS)
                print(">", end="")

    def parse_input(self):
        user_input = input().strip()
        input_parts = user_input.split(" ")
        operation = input_parts[0].upper()
        func_to_exec = self.user_input_handlers_map.get(
            operation, InteractiveModule.default_handler)
        return func_to_exec(input_parts[1:])

    def add_handler(self, args):
        if len(args) != 1:
            err_print("Exactly 1 argument required!")
            return False

        operand = float(args[0])
        self.rbtree.add_node(operand)
        print("Addition done!")
        return False

    def remove_handler(self, args):
        if len(args) != 1:
            err_print("Exactly 1 argument required!")
            return False

        print("RB Tree removal is not implemented!")
        return False

    def clear_tree_handler(self, args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        self.rbtree = RBTree()
        print("The tree has been cleared!")
        return False

    def contains_handler(self, args):
        if len(args) != 1:
            err_print("Exactly 1 argument required!")
            return False

        operand = float(args[0])
        res = self.rbtree.find_node(operand)
        if res:
            print("Tree contains that node!")
        else:
            print("Tree does not contain that node!")
        return False

    def size_handler(self, args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        print(f"Tree size is: {self.rbtree.get_size()}")
        return False

    def print_handler(self, args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        print("Printing the tree!")
        print(self.rbtree)
        return False

    def toggle_null_display_handler(self, args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        if self.rbtree.display_null_leaves:
            self.rbtree.display_null_leaves = False
            print("Turning off NULL leaves display!")
        else:
            self.rbtree.display_null_leaves = True
            print("Turning on NULL leaves display!")
        return False

    def toggle_colour_display_handler(self, args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        if self.rbtree.display_colours:
            self.rbtree.display_colours = False
            print("Turning off colour display!")
        else:
            self.rbtree.display_colours = True
            print("Turning on colour display!")
        return False

    def preorder_handler(self, args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        self.rbtree.preorder_traversal()
        return False

    def inorder_handler(self, args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        self.rbtree.inorder_traversal()
        return False

    def postorder_handler(self, args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        self.rbtree.postorder_traversal()
        return False

    def bfs_handler(self, args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        self.rbtree.bfs_traversal()
        return False

    @staticmethod
    def quit_handler(args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        return True  # Returning True signals that we should exit!

    @staticmethod
    def help_handler(args):
        if len(args) != 0:
            err_print("No arguments should be present for this operation!")
            return False

        print(InteractiveModule.__help_string)
        return False

    @staticmethod
    def default_handler(args):
        err_print("Unrecognised operation!")
        return False