示例#1
0
def make_tree(previous):
    """Сonstructing a game tree, by extending 
    (by adding two child vertices) from the root of a tree """
    # previous it is Board()
    if previous.if_won() == -1 or previous.if_won() == 1:
        return None
    
    new_move_left = random.choice(previous.empty_list())
    tree = LinkedBinaryTree(previous)

    if len(previous.empty_list()) == 0:
        return None
    new_previous = copy.deepcopy(previous)
    new_previous.set_null(new_move_left)

    tree.left_child = LinkedBinaryTree(new_previous)
    make_tree(new_previous)
    
    if len(new_previous.empty_list()) == 0:
        return None
    new_move_right = random.choice(new_previous.empty_list())
    n_new_previous = copy.deepcopy(new_previous)
    n_new_previous.set_null(new_move_right)

    tree.right_child = LinkedBinaryTree(n_new_previous)
    make_tree(n_new_previous)
示例#2
0
def main():
    gs = GS()
    print("To terminate game, type -1 -1")
    usrstep = gs.getUserStep()

    while usrstep[0] != -1:

        gs.make_step(gs.board(), usrstep[0], usrstep[1], Board.CROSS_CELL)

        if gs.board().check_for_win_combos(Board.CROSS_CELL):
            print(gs.board())
            print("CONGRATULATIONS! YOU WON!")
            break
        elif gs.board().is_full():
            print("TIGHT!")

        # generate two possible steps
        option1 = gs.generate_step(gs.board())
        option2 = gs.generate_step(gs.board())

        cross = gs.board().get_cross_cells()
        zeros = gs.board().get_zero_cells()

        # build two new boards
        board1 = Board(3, 3)
        board1.configure(cross.append(option1))
        board1.configure(zeros)

        board2 = Board(3, 3)
        board2.configure(cross[:-1].append(option2))
        board2.configure(zeros)

        # build two new decision binary trees
        tree1 = LinkedBinaryTree(board1)
        tree2 = LinkedBinaryTree(board2)

        # calculate the number of victories for each tree
        gs.fill_board(tree1, tree1)
        result1 = gs.get_numVictories()

        gs.clear_victories()

        gs.fill_board(tree2, tree2)
        result2 = gs.get_numVictories()

        # choose the step with the biggest number of victories
        if result1 > result2:
            gs.make_step(gs.board(), option1[0], option1[1], Board.ZERO_CELL)
        else:
            gs.make_step(gs.board(), option2[0], option2[1], Board.ZERO_CELL)

        print(gs.board())
        if gs.board().check_for_win_combos():
            print("YOU LOST!")
            break
        elif gs.board().check_for_win_combos(Board.CROSS_CELL):
            print("CONGRATULATIONS! YOU WON!")
            break
        print("To terminate game, type -1 -1")
        usrstep = gs.getUserStep()
示例#3
0
 def test_attach(self):
     """Tests for the nonpublic _attach method, mainly to hit inherited public
     methods that it will call."""
     new_tree = LinkedBinaryTree()
     ntroot = new_tree._add_root("New tree root")
     new_tree._add_left(ntroot, "NT left")
     new_tree._add_right(ntroot, "NT right")
     new_tree2 = LinkedBinaryTree()
     nt2root = new_tree2._add_root("2nd new tree root")
     new_tree2._add_left(nt2root, "left")
     new_tree2._add_right(nt2root, "right")
     self.tree._attach(self.lev3_first_left, new_tree, new_tree2)
示例#4
0
def build_UNIST_tree():
    """
    This function should return a binary tree that contains (a simplified and fictitious  version of) the organisational
    structure of schools and departments at UNIST. In particular, this function should return the following tree:
`+-*
    UNIST
    --Engineering
    ----Management Engineering
    ------Big data
    ------Business process management
    ----Materials Engineering
    ------Wood
    ------Plastic
    --Business
    ----Business Administration

    :return: the UNIST tree
    """
    UNIST = LinkedBinaryTree()
    root = UNIST._add_root("UNIST")
    EE = UNIST._add_left(root, "Engineering")
    BU = UNIST._add_right(root, "Bussiness")

    MNE = UNIST._add_left(EE, "Management Engineering")
    UNIST._add_left(MNE, "Big data")
    UNIST._add_right(MNE, "Business process management")
    MTE = UNIST._add_right(EE, "Material Engineering")
    UNIST._add_left(MTE, "Wood")
    UNIST._add_right(MTE, "Plastic")

    UNIST._add_left(BU, "Business Administration")

    return UNIST
示例#5
0
def build_UNIST_tree():
    """
    This function returns a (linked) binary tree that contains (a simplified and fictitious  version of)
    the organisational structure of schools and departments at UNIST.
    In particular, this function should return the following tree:
    
    UNIST
    --Engineering
    ----Management Engineering
    ------Big datastore
    ------Business process management
    ----Materials Engineering
    ------Wood
    ------Plastic
    --Business
    ----Business Administration

    """
    tree = LinkedBinaryTree()
    root = tree._add_root("UNIST")
    p_eng = tree._add_left(root, "Engineering")
    p_business = tree._add_right(root, "Business")
    p_man_eng = tree._add_left(p_eng, "Management Engineering")
    p_big_data = tree._add_left(p_man_eng, "Big datastore")
    p_bpm = tree._add_right(p_man_eng, "Business process management")
    p_mat_eng = tree._add_right(p_eng, "Materials Engineering")
    p_ba = tree._add_left(p_business, "Business Administration")
    return tree
示例#6
0
 def setUp(self):
     self.tree = LinkedBinaryTree()
     self.root = self.tree._add_root(1)
     self.element2 = self.tree._add_left(self.root, 2)
     self.element3 = self.tree._add_right(self.root, 3)
     self.element4 = self.tree._add_left(self.element2, 4)
     self.element5 = self.tree._add_right(self.element2, 5)
     self.element6 = self.tree._add_left(self.element3, 6)
     self.element7 = self.tree._add_right(self.element3, 7)
示例#7
0
def construct_num_tree():
    t = LinkedBinaryTree()
    root = t._add_root(0)
    l = t._add_left(root, 1)
    r = t._add_right(root, 2)

    t1 = LinkedBinaryTree()
    root = t1._add_root(3)
    left = t1._add_left(root, 5)
    right = t1._add_right(root, 6)

    t2 = LinkedBinaryTree()
    root = t2._add_root(4)
    left = t2._add_left(root, 7)
    right = t2._add_right(root, 8)

    t._attach(l, t1, t2)
    return t
示例#8
0
def construct_tree():
    t = LinkedBinaryTree()
    root = t._add_root('Trees')
    l = t._add_left(root, 'General trees')
    r = t._add_right(root, 'Binary trees')

    t1 = LinkedBinaryTree()
    root = t1._add_root('section1')
    left = t1._add_left(root, 'paragraph1')
    right = t1._add_right(root, 'paragraph2')

    t2 = LinkedBinaryTree()
    root = t2._add_root('section2')
    left = t2._add_left(root, 'paragraph1')
    right = t2._add_right(root, 'paragraph2')

    t._attach(l, t1, t2)
    return t
示例#9
0
 def setUp(self):
     self.tree = LinkedBinaryTree()
     # Create a proper balanced tree with 3 levels (8 elements)
     self.root = self.tree._add_root("Root")
     self.left = self.tree._add_left(self.root, "L2 left child")
     self.right = self.tree._add_right(self.root, "L2 right child")
     self.lev3_first_left = self.tree._add_left(self.left, "L3 left-1")
     self.tree._add_right(self.left, "L3 right-1")
     self.tree._add_left(self.right, "L3 left-2")
     self.tree._add_right(self.right, "L3 right-2")
示例#10
0
    def _compose_ht_tree(self, text):
        """Huffman tree construction for text."""
        freq_table = self._compute_chr_freq(text)
        ht_queue = HeapPriorityQueue()
        for freq, lett in freq_table:
            ht_tree = LinkedBinaryTree()
            ht_tree._add_root((freq, lett))
            ht_queue.add(freq, ht_tree)

        while len(ht_queue) > 1:
            (freq1, subtree1) = ht_queue.remove_min()
            (freq2, subtree2) = ht_queue.remove_min()
            freq = freq1 + freq2
            ht_tree = LinkedBinaryTree()
            ht_tree._add_root((freq, None))
            ht_tree._attach(ht_tree.root(), subtree1, subtree2)
            ht_queue.add(freq, ht_tree)
        _, ht_tree = ht_queue.remove_min()
        return ht_tree
示例#11
0
def build_tree(b):
    if b.someone_wins == "TIE" or b.someone_wins == "O" or b.someone_wins == "X":
        return

    tree = LinkedBinaryTree(b)
    free_cells = b.empty_coords
    random_cell1 = choice(list(free_cells))
    choice1 = deepcopy(b)
    choice1.turn("O", random_cell1)
    tree.left_child = LinkedBinaryTree(choice1)
    build_tree(choice1)

    free_cells.discard(random_cell1)
    if free_cells != set():  # we have to check if set isn't empty
        random_cell2 = choice(list(free_cells))
        choice2 = deepcopy(b)
        choice2.turn("O", random_cell2)
        tree.right_child = LinkedBinaryTree(choice2)
        build_tree(choice2)
示例#12
0
 def test_validate(self):
     # Passing an object of type other than Position should raise TypeError
     with self.assertRaises(TypeError):
         self.tree._validate("spam")
     # Wrong container should raise value error
     position_from_other_container = LinkedBinaryTree()._add_root(
         "spam root")
     with self.assertRaises(ValueError):
         self.tree._validate(position_from_other_container)
     # If node was deprecated, meaning it was set to be its own parent per
     #   the internal convention for deprecated nodes, then should raise
     #   value error.
     p = self.lev3_first_left
     p._node._parent = p._node
     with self.assertRaises(ValueError):
         self.tree._validate(p)
def create_tree():
    t = LinkedBinaryTree()
    f = t._add_root('f')

    # left tree
    b = t._add_left(f, 'b')
    t._add_left(b, 'a')
    d = t._add_right(b, 'd')
    t._add_left(d, 'c')
    t._add_right(d, 'e')

    # right tree
    g = t._add_right(f, 'g')
    i = t._add_right(g, 'i')
    t._add_left(i, 'h')
    return t
示例#14
0
    def build_tree(self):
        """
        Builds the game tree
        :return: object
        """
        game_tree = LinkedBinaryTree()
        board = self.board
        game_tree._add_root(Board(board))

        def add_board(tree, node):
            """
            adds new board to a tree
            :param tree: object
            :param node: object
            :return: None
            """
            positions = self.available_positions(node._element)
            if not positions:
                return None
            if tree.height() == tree.depth(tree._make_position(node)) \
                    and tree.height() % 2 == 0:
                symbol = 'o'
            else:
                symbol = 'x'
            pos = random.choice(positions)
            new_board = Board(node._element.board)
            new_board.board[pos[0], pos[1]] = symbol
            tree._add_left(tree._make_position(node), Board(new_board.board))
            positions = self.available_positions(new_board)
            if not positions:
                return None
            pos = random.choice(positions)
            new_board = Board(node._element.board)
            new_board.board[pos[0], pos[1]] = symbol
            tree._add_right(tree._make_position(node), Board(new_board.board))
            add_board(tree, node._left)
            add_board(tree, node._right)

        add_board(game_tree, game_tree._root)
        return game_tree
示例#15
0
from linked_binary_tree import LinkedBinaryTree

test_tr = LinkedBinaryTree(' a')
print(test_tr)
print("root_val ", test_tr.get_root_val())
print("left_child ", test_tr.get_left_child())
test_tr.insert_left(' b')
print("left_child ", test_tr.get_left_child())
print("left_child().get_root_val ", test_tr.get_left_child().get_root_val())
test_tr.insert_right(' c')
print("right_child ", test_tr.get_right_child())
print("right_child().get_root_val ", test_tr.get_right_child().get_root_val())
r.get_right_child().set_root_val(' hello')
print("right_child().get_root_val", test_tr.get_right_child().get_root_val())

print(test_tr)
示例#16
0
from linked_binary_tree import LinkedBinaryTree

test_tr = LinkedBinaryTree(' a')
#test_tr.is_empty()
print(test_tr)
print("root_val ", test_tr.get_root_val())
print("left_child ", test_tr.get_left_child())
test_tr.insert_left(' b')
print("left_child ", test_tr.get_left_child())
print("left_child().get_root_val ", test_tr.get_left_child().get_root_val())

test_tr.insert_left(' bb')
print("left_child ", test_tr.get_left_child())
print("left_child().get_root_val ", test_tr.get_left_child().get_root_val())

test_tr.insert_right(' c')
print("right_child ", test_tr.get_right_child())
print("right_child().get_root_val ", test_tr.get_right_child().get_root_val())
test_tr.get_right_child().set_root_val(' hello')
print("right_child().get_root_val", test_tr.get_right_child().get_root_val())

test_tr.inorder()

a_node = LinkedBinaryTree('A')
a_node.insert_left('B')
a_node.insert_right('C')

b_node = a_node.left_child
b_node.insert_right('D')

c_node = a_node.right_child
示例#17
0
"""Preorder traversal"""

# 应该使用普通的树而不是二叉树
from linked_binary_tree import LinkedBinaryTree

# Electronics R’Us
#   1 R&D
#   2 Sales
#     2.1 Domestic
#     2.2 International
#       2.2.1 Canada
#       2.2.2 America
toc = LinkedBinaryTree()
toc._add_root('Electronics R’Us')
toc._add_left(toc.root(), 'R&D')
toc._add_right(toc.root(), 'Sales')
toc._add_left(toc.right(toc.root()), 'Domestic')
toc._add_right(toc.right(toc.root()), 'International')
toc._add_left(toc.right(toc.right(toc.root())), 'Canada')
toc._add_right(toc.right(toc.right(toc.root())), 'America')


def parenthesize(t, p, rep):
    if t.is_empty():
        return

    rep += str(p.element())

    if not t.is_leaf(p):
        first_time = True
        for c in t.children(p):
示例#18
0
 def __init__(self):
     self.cells = [[0] * 3 for _ in range(3)]
     self.last_move = Board.NOUGHT
     self.number_of_moves = 0
     self.status = None
     self.tree = LinkedBinaryTree(self)
示例#19
0
 def test_root(self):
     blank_tree = LinkedBinaryTree()
     root = blank_tree.root()
     self.assertEqual(root, None)  # Should return None for an empty tree.
     root = self.tree.root()
     self.assertEqual(root.element(), "Root")