コード例 #1
0
def test_bst(lst):
    bst = LinkedBST()
    for i in lst:
        bst.add(i)
    start = time.time()
    for i in range(10**4):
        word = random.choice(lst)
        word1 = bst.find(word)
        assert word == word1
    return time.time() - start
コード例 #2
0
def make_tree(info):
    """
    Filling the Binary Search Tree structure
    info: set with words
    return: Tree
    """
    tree = LinkedBST()
    for i in info:
        tree.add(i)
    return tree
コード例 #3
0
        def build_states(cur_state):
            """
            Builds a tree of states starting from the current game state.
            Always chooses 2 random move options. (god knows why it's stupid)
            This method pre-fills the terminal states with scores of 1, -1, and 0.
            :param cur_state: Game
            :return: LinkedBST
            """
            states = LinkedBST()
            st = LinkedStack()
            states.root = BSTNode([deepcopy(cur_state.board), None, None])
            st.push(states.root)

            while not st.isEmpty():
                curr = st.pop()
                curr_board = curr.data[0]
                p1w = curr_board.game_over(player=1)
                p2w = curr_board.game_over(player=2)

                if p1w:
                    curr.data[1] = 1
                    continue
                elif p2w:
                    curr.data[1] = -1
                    continue

                cells = curr.data[0].free_cells()
                if not cells:
                    # No one won and no cells left - it's a tie.
                    curr.data[1] = 0
                    continue

                available = random.sample(cells, k=min(len(cells), 2))
                for cell in available:
                    new_board = deepcopy(curr.data[0].move(
                        cell,
                        player=1 if curr.data[0].get_turn() % 2 == 1 else 2))
                    curr.data[0].undo(cell)
                    if curr.left is None:
                        curr.left = BSTNode([new_board, None, cell])
                        st.add(curr.left)
                    elif curr.right is None:
                        curr.right = BSTNode([new_board, None, cell])
                        st.add(curr.right)
                    else:
                        break

            return states
コード例 #4
0
def search_in_balanced_tree():
    """
    return time to search for 1000 words in the balanced tree
    :return: float
    """
    tree = LinkedBST()
    sys.setrecursionlimit(150000)
    for word in readed_file:
        tree.add(word)
    tree.rebalance()
    start = time.time()
    for i in range(1000):
        tree.find(random_word())
    return time.time() - start
コード例 #5
0
def main():
    tmp_set, tmp_list = read_file('words.txt'), []
    searching_list = []
    counter = 0
    while True:
        try:
            tmp_list.append(tmp_set.pop())
            counter += 1
        except KeyError:
            break
    tmp_set = read_file('words.txt')
    counter = 0
    while counter < 10000:
        counter += 1
        searching_list.append(tmp_set.pop())
    tree = LinkedBST(tmp_list)
    print(
        'a) визначити час пошуку 10000 випадкових слів у впорядкованому за абеткою словнику (пошук у списку слів з використанням методів вбудованого типу list).'
    )
    time1 = time.time()
    for word in searching_list:
        l1 = tmp_list.index(word)
    print(time.time() - time1)

    print(
        'b) визначити час пошуку 10000 випадкових слів у словнику, який представлений у вигляді бінарного дерева пошуку. Бінарне дерево пошуку будується на основі словника в якому слова не впорядковані за абеткою. '
    )
    time1 = time.time()
    for word in searching_list:
        tree.find(word)
    print(time.time() - time1)

    if not tree.is_balanced():
        tree.rebalance()

    print(
        'c) Визначити час пошуку 10000 випадкових слів у словнику, який представлений у вигляді збалансованого бінарного дерева пошуку.'
    )

    time1 = time.time()
    for word in searching_list:
        tree.find(word)
    print(time.time() - time1)
コード例 #6
0
def bst_search(words, selected_words):

    found = list()
    tree = LinkedBST()

    def BSTConverter(lst_to_convert):

        if len(lst_to_convert) == 0:

            return None

        mid = len(lst_to_convert) // 2
        node = BSTNode(lst_to_convert[mid])
        node.left = BSTConverter(lst_to_convert[:mid])
        node.right = BSTConverter(lst_to_convert[mid + 1:])
        return node

    tree._root = BSTConverter(words)
    for word in selected_words:

        tree.find(word)
        found.append(word)

    return found
コード例 #7
0
def binary_tree_search(words, selected_words):

    found = list()
    tree = LinkedBST()
    for word in words:

        tree.add(word)

    for word in selected_words:

        tree.find(word)
        found.append(word)

    return found
コード例 #8
0
def main():
    tree = LinkedBST()
    print("Adding D B A C F E G")
    tree.add("D")
    tree.add("B")
    tree.add("A")
    tree.add("C")
    tree.add("F")
    tree.add("E")
    tree.add("G")

    print("\nExpect True for A in tree: ", "A" in tree)

    print("\nString:\n" + str(tree))

    clone = LinkedBST(tree)
    print("\nClone:\n" + str(clone))

    print("Expect True for tree == clone: ", tree == clone)

    print("\nFor loop: ", end="")
    for item in tree:
        print(item, end=" ")

    print("\n\ninorder traversal: ", end="")
    for item in tree.inorder(): print(item, end=" ")

    # print("\n\npreorder traversal: ", end="")
    # for item in tree.preorder(): print(item, end = " ")

    # print("\n\npostorder traversal: ", end="")
    # for item in tree.postorder(): print(item, end = " ")

    # print("\n\nlevelorder traversal: ", end="")
    # for item in tree.levelorder(): print(item, end = " ")

    print("\n\nRemoving all items:", end=" ")
    for item in "ABCDEFG":
        print(tree.remove(item), end=" ")

    print("\n\nExpect 0: ", len(tree))

    tree = LinkedBST(range(1, 16))
    print("\nAdded 1..15:\n" + str(tree))

    lyst = list(range(1, 16))

    random.shuffle(lyst)
    tree = LinkedBST(lyst)
    print("\nAdded ", lyst, "\n" + str(tree))

    lyst = [113, 30, 68, 74, 45, 91, 88]
    # random.shuffle(lyst)
    tree = LinkedBST(lyst)
    print(tree, tree.height())
    print(tree.isBalanced())
    print(tree.rangeFind(30, 91))
    print(tree.successor(20))
    print(tree.predecessor(50))
    tree.rebalance()
    print(tree)
コード例 #9
0
from binary_search_tree.linkedbst import LinkedBST

tree = LinkedBST()
tree.add("A")
tree.add("B")
tree.add("C")
tree.add("D")
tree.add("E")
tree.add("F")
tree.add("G")
tree.add("H")
tree.add("I")
tree.add("J")
tree.add("K")

print(tree)
print("Answer must be False: ", tree.isBalanced())
tree.rebalance()
print(tree)
print("Answer must be True: \n", tree.isBalanced())
print("Answer must be D : \n", tree.successor("C").data)
print("Answer must be B : \n", tree.predecessor("C").data)
print("Answer must be C: \n")
for i in tree.rangeFind("B", "D"):
    print(i.data)
コード例 #10
0
ファイル: game.py プロジェクト: popenyuk/Tic-Tac-Toe
class Game:
    """
    represent game in tic tac toe
    """
    def __init__(self):
        self._board = Board()

    def _build_tree(self):
        """
        build tree with random move for computer
        :return: None
        """

        def recurse(p):
            """
            make new board for branch
            :param p: BSTNode
            :return: None
            """
            if p is not None and p.data.check_win() is None:
                new_board = Board()
                for i in range(3):
                    for j in range(3):
                        new_board.add_value(i, j,
                                            p.data._game_board[i, j])
                move1_x = random.randint(0, 2)
                move1_y = random.randint(0, 2)
                move2_x = random.randint(0, 2)
                move2_y = random.randint(0, 2)

                while not new_board.is_good_move(move1_x, move1_y):
                    move1_x = random.randint(0, 2)
                    move1_y = random.randint(0, 2)
                new_board.second_player_move(move1_x, move1_y)

                if new_board.check_win() is None:
                    while not new_board.is_good_move(move2_x,
                                                     move2_y) or (
                            move1_x == move2_x and move1_y == move2_y):
                        move2_x = random.randint(0, 2)
                        move2_y = random.randint(0, 2)
                    new_board.first_player_move(move2_x, move2_y)

                self._builded_tree._add_right(p, new_board)
                recurse(self._builded_tree.super_find(new_board))

                if new_board.check_win() is None:
                    for i in range(3):
                        for j in range(3):
                            new_board.add_value(i, j,
                                                p.data._game_board[i, j])

                    move1_x = random.randint(0, 2)
                    move1_y = random.randint(0, 2)
                    move2_x = random.randint(0, 2)
                    move2_y = random.randint(0, 2)
                    while not new_board.is_good_move(move1_x, move1_y):
                        move1_x = random.randint(0, 2)
                        move1_y = random.randint(0, 2)

                    new_board.second_player_move(move1_x, move1_y)
                    if new_board.check_win() is None:
                        while not new_board.is_good_move(move2_x,
                                                         move2_y) or (
                                move1_x == move2_x and move1_y == move2_y):
                            move2_x = random.randint(0, 2)
                            move2_y = random.randint(0, 2)
                        new_board.first_player_move(move2_x, move2_y)

                    self._builded_tree._add_left(p, new_board)
                    recurse(self._builded_tree.super_find(new_board))
            return None

        self._builded_tree = LinkedBST()
        self._builded_tree.add(self._board)
        recurse(self._builded_tree.find(self._board))

    def search_max(self):
        """
        calculate which move computer is better
        :return: None
        """
        def recurse(item):
            """
            calculate how many points have branch
            :param item: BSTNode
            :return: int
            """
            if item is None:
                return 0
            if item.data.check_win() is not None and item.right is None and item.left is None:
                if item.data.check_win() == "draw":
                    return 0
                elif item.data.check_win()[1] == "first player win":
                    return -1
                else:
                    return 1
            else:
                try:
                    item.right
                    try:
                        item.left
                        return recurse(item.right) + recurse(item.left)
                    except:
                        return recurse(item.right)
                except:
                    try:
                        item.left
                        return recurse(item.left)
                    except:
                        return 0

        item = self._builded_tree._root
        left_item = item.left
        rigth_item = item.right
        print(recurse(left_item), recurse(rigth_item))
        if recurse(left_item) >= recurse(rigth_item):
            return "left"
        else:
            return "right"

    def move_computer(self):
        """
        generate computer move
        :return: None
        """
        self._build_tree()
        max = self.search_max()
        if max == "left" and self._builded_tree._root.left is not None:
            self._board = self._builded_tree._root.left.data
            row = self._builded_tree._root.left.data._last_move[0]
            col = self._builded_tree._root.left.data._last_move[1]
            if self._board._game_board[row, col] == "x":
                self._board.add_value(row, col, None)
        elif self._builded_tree._root.right is not None:
            self._board = self._builded_tree._root.right.data
            row = self._builded_tree._root.right.data._last_move[0]
            col = self._builded_tree._root.right.data._last_move[1]
            if self._board._game_board[row, col] == "x":
                self._board.add_value(row, col, None)

    def run(self):
        """
        run game
        :return: None
        """
        def check_win():
            """
            check if someone win
            :return: None
            """
            if self._board.check_win() is not None:
                if self._board.check_win() == "draw":
                    print("Draw!")
                elif self._board.check_win()[1] == "first player win":
                    print("You win!")
                else:
                    print("You lose!")
                sys.exit()

        print("Hello!")
        print("Let`s play game/ You will be move first because if you move "
              "second you will lose")

        while not self._board.check_win():
            move1 = int(input("Input your row move: "))
            move2 = int(input("Input your col move: "))

            while not self._board.is_good_move(move1, move2):
                move1 = int(input("Reinput your row move: "))
                move2 = int(input("Reinput your col move: "))

            self._board.first_player_move(move1, move2)
            check_win()
            print("Your move\n", self._board)
            self.move_computer()
            print("Computer move\n", self._board)
            check_win()
コード例 #11
0
ファイル: game.py プロジェクト: popenyuk/Tic-Tac-Toe
    def _build_tree(self):
        """
        build tree with random move for computer
        :return: None
        """

        def recurse(p):
            """
            make new board for branch
            :param p: BSTNode
            :return: None
            """
            if p is not None and p.data.check_win() is None:
                new_board = Board()
                for i in range(3):
                    for j in range(3):
                        new_board.add_value(i, j,
                                            p.data._game_board[i, j])
                move1_x = random.randint(0, 2)
                move1_y = random.randint(0, 2)
                move2_x = random.randint(0, 2)
                move2_y = random.randint(0, 2)

                while not new_board.is_good_move(move1_x, move1_y):
                    move1_x = random.randint(0, 2)
                    move1_y = random.randint(0, 2)
                new_board.second_player_move(move1_x, move1_y)

                if new_board.check_win() is None:
                    while not new_board.is_good_move(move2_x,
                                                     move2_y) or (
                            move1_x == move2_x and move1_y == move2_y):
                        move2_x = random.randint(0, 2)
                        move2_y = random.randint(0, 2)
                    new_board.first_player_move(move2_x, move2_y)

                self._builded_tree._add_right(p, new_board)
                recurse(self._builded_tree.super_find(new_board))

                if new_board.check_win() is None:
                    for i in range(3):
                        for j in range(3):
                            new_board.add_value(i, j,
                                                p.data._game_board[i, j])

                    move1_x = random.randint(0, 2)
                    move1_y = random.randint(0, 2)
                    move2_x = random.randint(0, 2)
                    move2_y = random.randint(0, 2)
                    while not new_board.is_good_move(move1_x, move1_y):
                        move1_x = random.randint(0, 2)
                        move1_y = random.randint(0, 2)

                    new_board.second_player_move(move1_x, move1_y)
                    if new_board.check_win() is None:
                        while not new_board.is_good_move(move2_x,
                                                         move2_y) or (
                                move1_x == move2_x and move1_y == move2_y):
                            move2_x = random.randint(0, 2)
                            move2_y = random.randint(0, 2)
                        new_board.first_player_move(move2_x, move2_y)

                    self._builded_tree._add_left(p, new_board)
                    recurse(self._builded_tree.super_find(new_board))
            return None

        self._builded_tree = LinkedBST()
        self._builded_tree.add(self._board)
        recurse(self._builded_tree.find(self._board))