コード例 #1
0
    def test_free_tests(self):
        print("\n ** FREE TESTS **") 
        """Actions: add, search and remove  N (define below) items 
           Expected result: Find all items and have empty tree "()" """
    
        bt = BinTree()
        N = 2**10

        btDataSet = set()
        while len(btDataSet) < N:
           btDataSet.add(randint(0,N)) # this approach is horrible...
        btData = [e for e in btDataSet] 
        #print("TEST DATA : Input {}".format(btData))
        shuffle(btData)
        for d in btData:
            bt.insert(d)
            #print("After inserting {}, we got {}".format(d, bt))
        #print("Resulted Tree : {}".format(bt))
        shuffle(btData)
        for d in btData:
            tempBt = bt.search(d)
            if not tempBt:
                print("FAILED to find existing item {}".format(d)) 
        shuffle(btData)
        for d in btData:
            result = bt.delete(d)
            #print("After deleting {}, we got {}".format(d, bt))
            if not result:
                print("FAILED : could not delete {}.".format(d))
        if str(bt) != "()":
            print("FAILED : tree is not empty after deleting all nodes. Got {}".format(bt))
        elif len(bt) != 0:
            print("FAILED : tree is not empty after deleting all nodes. Tree is has {} nodes".format(len(bt)))
        else:
            print("INSERTED, SEARCHED and DELETED {} items.".format(N)) 
コード例 #2
0
ファイル: test_bintree.py プロジェクト: marcinowski/trees
 def test_insertion_left(self):
     """
             3
            /
           2
     """
     b = BinTree(3)
     b.insert(2)
     self.assertIsInstance(b.left_child, BinTree)
     self.assertIsNone(b.right_child)
コード例 #3
0
def gen_random_tree(n, a, b, root=None, free=None):
    if n == 0:
        return root
    if root == None:
        root = BinTree(randint(a, b))
        free = [(root, 0), (root, 1)]
    else:
        node, side = free.pop(randint(0, len(free) - 1))
        new_node = BinTree(randint(a, b))
        free.extend([(new_node, 0), (new_node, 1)])
        if side:
            node.right = new_node
        else:
            node.left = new_node
    return gen_random_tree(n - 1, a, b, root, free)
コード例 #4
0
    def parse(cls, tokens):
        # parentheses:
        #   find leftmost ")"
        #   find rightmost "("
        #   parse everything in between and replace it with the result
        while True:
            for close_index, t in enumerate(tokens):
                if isinstance(t, CloseParenthesis):
                    break
            else:  # no closing parenthesis
                break
            for open_index in range(close_index - 1, -1, -1):
                t = tokens[open_index]
                if isinstance(t, OpenParenthesis):
                    break
            else:  # open parenthesis not found, unbalanced parentheses
                # TODO better error message including the token's span
                raise ValueError("unbalanced parentheses")
            tree = cls.parse(tokens[open_index + 1:close_index])
            tokens = tokens[:open_index] + [tree] + tokens[close_index + 1:]

        for group in Operators.ALL_OPERATORS:
            while True:
                for index, t in enumerate(tokens):
                    if not isinstance(t, Operator):
                        continue
                    if t in group:
                        break
                else:  # did not find an operator in wanted group
                    break
                tree = BinTree(t, tokens[index - 1], tokens[index + 1])
                tokens = tokens[:index - 1] + [tree] + tokens[index + 2:]
        assert len(tokens) == 1, ("%s did not consume all tokens" %
                                  (cls.__name__, ))
        return tokens[0]
コード例 #5
0
ファイル: test_bintree.py プロジェクト: marcinowski/trees
class TestInserting(TestCase):
    def test_insertion_right(self):
            """
                3
                 \
                  4
            """
        b = BinTree(3)
        b.insert(4)
        self.assertIsInstance(b.right_child, BinTree)
        self.assertIsNone(b.left_child)
コード例 #6
0
ファイル: bintree_test.py プロジェクト: ms16769/exercise-06
 def test_example(self):
     values = [7, 3, 9, 2, 4, 8, 11]
     tree = BinTree()
     for value in values:
         tree.insert(value)
     for value in values:
         node = tree.search(value)
         self.assertIsInstance(node, BinTreeNode)
         self.assertEqual(value, node.value)
     node = tree.search(3)
     self.assertEqual(node.value, 3)
     self.assertEqual(node.left.value, 2)
     self.assertEqual(node.right.value, 4)
コード例 #7
0
ファイル: test_bintree.py プロジェクト: marcinowski/trees
 def test_removing_non_branched_child(self):
     """
             6
              \
               10
               /
              8
               \
                9
         =>
             6
              \
               9
              /
             8
     """
     b = BinTree(6)
     b.insert_many(10, 8, 9)
     b.remove(10)
     self.assertEqual(b.right_child.value, 9)
     self.assertEqual(b.to_list(), [6, 8, 9])
     self.assertEqual(b.depth(), 3)
コード例 #8
0
def get_line():
    """
    Gets a line from the input. Returns whether there was a valid line.
    This will initialize the ``curr`` and ``linetok`` attributes.
    """
    global linetok, currLine, curr, currTest

    line = ''

    while line.startswith('#') or len(line) == 0:
        currLine += 1
        try:
            line = lines.pop(0)
        except IndexError:
            return False

        line = line.strip()

    linetok = line.split()
    first = linetok.pop(0)
    if first == "C":
        # Keep current BinTree
        pass
    elif first == "S":
        print("Reading saved tree")
        curr = save.clone()
        currTest = set(saveTest)
    elif first == "B":
        print("Creating BinTree")
        curr = BinTree()
        currTest = set()
    else:
        print("Unidentified token {} on line {}".format(first, currLine))
        exit(1)

    return True
コード例 #9
0
ファイル: bintree_test.py プロジェクト: ms16769/exercise-06
 def test_create_has_root_none(self):
     tree = BinTree()
     self.assertIsNone(tree.root)
コード例 #10
0
ファイル: bintree_test.py プロジェクト: ms16769/exercise-06
 def test_insert_into_empty_tree(self):
     tree = BinTree()
     tree.insert(1)
     self.assertIsNotNone(tree.root)
     self.assertIsInstance(tree.root, BinTreeNode)
     self.assertEqual(tree.root.value, 1)
コード例 #11
0
ファイル: bintree_test.py プロジェクト: ms16769/exercise-06
 def test_has_insert_and_search(self):
     tree = BinTree()
     tree.insert(1)
     self.assertIsInstance(tree.search(1), BinTreeNode)
     self.assertIsNone(tree.search(0))
コード例 #12
0
ファイル: test_bintree.py プロジェクト: marcinowski/trees
 def test_initialing_empty(self):
     b = BinTree()
     self.assertEqual(None, b.value)
     self.assertIsNone(b.right_child)
     self.assertIsNone(b.left_child)
コード例 #13
0
ファイル: test_bintree.py プロジェクト: marcinowski/trees
 def setUp(self):
     self.b = BinTree(3)
     self.b.insert_many(2, 5, 4, 6)
コード例 #14
0
ファイル: test_bintree.py プロジェクト: marcinowski/trees
class TestRemoving(TestCase):
    def setUp(self):
        self.b = BinTree(3)
        self.b.insert_many(2, 5, 4, 6)

    def test_removing_root(self):
        """
                3
              /   \
            2       5
                   / \
                  4   6
            =>
                4
              /   \
            2       5
                      \
                        6
        """
        self.b.remove(3)
        self.assertEqual(4, self.b.value)
        self.assertIsNone(self.b.right_child.left_child)
        self.assertEqual(self.b.to_list(), [2, 4, 5, 6])

    def test_removing_child(self):
        """
                3
              /   \
            2       5
                   / \
                  4   6
            =>
                3
              /   \
            2       4
                      \
                        6
        """
        self.b.remove(5)
        self.assertEqual(self.b.right_child.value, 4)
        self.assertEqual(self.b.to_list(), [2, 3, 4, 6])

    def test_removing_leaf(self):
        """
                3
              /   \
            2       5
                   / \
                  4   6
            =>
                3
              /   \
            2       5
                   /
                  4
            =>
                3
              /   \
            2       5
        """
        self.b.remove(6)
        self.assertEqual(self.b.to_list(), [2, 3, 4, 5])
        self.b.remove(4)
        self.assertEqual(self.b.depth(), 2)

    def test_removing_non_branched_child(self):
        """
                6
                 \
                  10
                  /
                 8
                  \
                   9
            =>
                6
                 \
                  9
                 /
                8
        """
        b = BinTree(6)
        b.insert_many(10, 8, 9)
        b.remove(10)
        self.assertEqual(b.right_child.value, 9)
        self.assertEqual(b.to_list(), [6, 8, 9])
        self.assertEqual(b.depth(), 3)
コード例 #15
0
ファイル: test_bintree.py プロジェクト: marcinowski/trees
 def test_initializing_value(self):
     b = BinTree(1)
     self.assertEqual(1, b.value)
     self.assertIsNone(b.right_child)
     self.assertIsNone(b.left_child)
コード例 #16
0
ファイル: main.py プロジェクト: nikita199801/binary_tree
from bintree import BinTree

new_tree = BinTree()
while True:
    choose = int(
        input("1. Ввести дерево \n"
              "2. Вывести дерево\n"
              "3. Вывести все возможные слова\n"
              "0. Выход\n"
              "Выберите пункт: "))
    if choose == 1:
        val = ""
        while val != " ":
            val = input("Введите узел: ")
            if val == " ":
                break
            else:
                new_tree.insert(val)
    elif choose == 2:
        new_tree.printTree(new_tree.getRoot())
    elif choose == 3:
        new_tree.printWrds(new_tree.getRoot())
        new_tree.nullFlag(new_tree.getRoot())
    elif choose == 0:
        break
new_tree.printTree(new_tree.getRoot())

# a=["f","w","b","e","a","t","u","l","d","z","s","q"]
# b=["ф","а","в","б","е","ц","с"]
コード例 #17
0
 def _create_BinTree(self, allNodes):
     bt = BinTree()
     for node in allNodes:
         bt.insert(node)
     return bt     
コード例 #18
0
from bintree import BinTree


def int_comp(curr, new):
    if curr > new:
        return 1
    elif curr < new:
        return -1
    else:
        return 0


b = BinTree(666)
print(b)

print(b.data)
print(b.left)
print(b.right)

b = b.insert(777, int_comp)
b = b.insert(888, int_comp)
b = b.insert(555, int_comp)

# b.left = BinTree(777)
# b.right = BinTree(888)

print(b.listify())