Principle of Computing (Python) Learning notes (7) DFS Search + Tic Tac Toe use MiniMax stratedy

Source: Internet
Author: User
Tags arithmetic operators

1. Trees

Tree is a recursive structure.

1.1 Math nodes

Https://class.coursera.org/principlescomputing-001/wiki/view?

Page=trees

1.2 Code no parent-domain tree

http://www.codeskulptor.org/#poc_tree. py

Class Tree: "" "Recursive definition for trees plus various Tree methods" "" Def __init__ (self, value, CHI Ldren): "" "Create a tree whose root has specific value (a string) children is a list of references T          o The roots of the subtrees.        "" "Self._value = value Self._children = children def __str__ (self):" ""                Generate a string representation of the tree use an pre-order traversal of the tree ""             Ans = "[" ans + = str (self._value) for Self._children:ans + = ","        Ans + = str (child) return-ans + "]" def get_value (self): "" "getters for node ' s value        "" "Return Self._value def Children (self):" "" "," "" Generator To return Children "" "  For Self._children:yield child def Num_nodes (self): "" "      Compute number of nodes in the tree "" "ans = 1 for child in Self._children:ans + = Child.num_nodes () return ans def num_leaves (self): "" ", Count number of leaves in tree"            "If Len (self._children) = = 0:return 1 ans = 0 for child in Self._children: Ans + = child.num_leaves () return ans def height (self): "" "Compute height of a tree rooted by self "" "height = 0 for child in self._children:height = max (height, child.height () +     1) return height def run_examples (): "" "Create some trees and apply various methods to these trees" ""    Tree_a = Tree ("A", []) Tree_b = tree ("B", []) print "tree consisting of single leaf node labelled ' a '", tree_a Print "tree consisting of single leaf node labelled ' B '", Tree_b Tree_cab = Tree ("C", [Tree_a, Tree_b]) print "Tree consisting of threE node ", Tree_cab Tree_dcabe = tree (" D ", [Tree_cab, Tree (" E ", [])]) print" tree consisting of five nodes ", Tree_ Dcabe Print My_tree = Tree ("A", [Tree ("B", [Tree ("C", []), Tree ("D", [])]), tree ("E",    [Tree ("F", [Tree ("G", [])]), tree ("H", []), Tree ("I", [])])) Print "Tree with Nine nodes", my_tree print "The Tree have", my_tree.num_nodes (), "nodes,", Print My_tree.num_le Aves (), "leaves and height", print my_tree.height () #import poc_draw_tree #poc_draw_tree. Treedisplay (My_tree) #run_examples ()


1.3 Code has the parent domain tree

http://www.codeskulptor.org/#user36_3SjNfYqJMV_4. PY

Import Poc_treeclass Navtree (Poc_tree. Tree): "" "Recursive definition for navigable trees plus extra tree Methods" "Def __init__ (self, value, Children, parent = None): "" "Create a tree whose root has specific value (a string) children is a Li          St of references to the roots of the children. The parent (if specified) is a reference to the tree ' s parent node "" Poc_tree. Tree.__init__ (self, value, children) Self._parent = parent to child in Self._children:child._pa Rent = Self def set_parent (self, parent): "" "Update parent Field" "" Self._p        arent = parent Def get_root (self): "" "Return the root of the tree" "        if self._parent = = None:return self;    Else:return Self._parent.get_root (); def depth (self): "" "Return the depth of the self with respect to the Root of the tree "" "Pass Def Run_examples ():" "" Create some trees and apply various methods to T     hese trees "" "Tree_a = Navtree (" A ", []) Tree_b = Navtree (" B ", []) Tree_cab = Navtree (" C ", [Tree_a, Tree_b]) Tree_e = Navtree ("E", []) Tree_dcabe = Navtree ("D", [Tree_cab, tree_e]) print "This is the main tree-", tree _dcabe print "This is the tree that contains B-", Tree_b.get_root () import Poc_draw_tree poc_draw_tree.             Treedisplay (Tree_dcabe) print "The Node B has depth", tree_b.depth () print "The node e has depth", tree_e.depth () Run_examples () # Expect Output#this is the main tree-[D, [C, [a], [b]], [e]]] #This was tree that contains B-[D , [C, [a], [b]], [e]] #The Node B have depth 2#the node E has depth 1

1.4 CODE Arithmetic expreesion is expressed by a tree.

Interior nodes in the tree is always arithmetic operators. The leaves of the tree is always numbers.

http://www.codeskulptor.org/#poc_arith_expression. py

# import Tree class Definitionimport poc_tree# use Dictionary of Lambdas to abstract function definitionsoperators = {"+"  : (lambda x, y:x + y), "-": (Lambda x, y:x-y), "*": (lambda x, y:x * y), "/": (lambda x, y:x/y), "//": (Lambda x, y:x//y), "%": (lambda x, y:x% y)}class Arithmetice Xpression (Poc_tree. Tree): "" "Basic Operations on Arithmetic Expressions" "" Def __init__ (self, value, children, parent = Non E): "" "Create an arithmetic expression as a tree" "Poc_tree. Tree.__init__ (self, value, children) def __str__ (self): "" "Generate A string Representat         Ion for an arithmetic expression "" "If Len (self._children) = = 0:return Str (self._value)         Ans = "(" ans + = str (self._children[0]) ans + = str (self._value) ans + = str (self._children[1]) Ans + = ")" Return ans                    def evaluate (self): "" "Evaluate the Arithmetic expression" "" if                Len (self._children) = = 0:if "." In Self._value:return float (self._value) Else: return int (self._value) else:function = Operators[self._value] Left_value = self. _children[0].evaluate () Right_value = self._children[1].evaluate () return function (Left_value, right _value) def run_example (): "" "Create and evaluate some examples of arithmetic expressions" "" one = Arithmeti  Cexpression ("1", [])-Arithmeticexpression ("2", []) three = Arithmeticexpression ("3", []) print one print One.evaluate () One_plus_two = arithmeticexpression ("+", [one, both]) print one_plus_two print One_plus_two.ev Aluate () One_plus_two_times_three = Arithmeticexpression ("*", [One_plus_two, three]) print one_plus_two_times_th REE Import POC_DRAw_tree Poc_draw_tree. Treedisplay (one_plus_two_times_three) print one_plus_two_times_three.evaluate () run_example ()

2 List


In Python, lists is primarily iterative data structures that is processed using loops. However, in other languages such as Lisp and Scheme, lists is treated primarily as recursive data structures and Processe D recursively.

2.1 A list example

Class NodeList: "" "Basic class definition for Non-empty lists using recursion" "" Def __init__ (self, Val) : "" "Create a list with one node" "" Self._value = val Self._next = None D EF Append (Self, Val): "" "append a node to an existing list of nodes" "" # print "---------call Ed---append ()--------\ n "If Self._next = = none:# print" A: "+str (Isinstance (val,int)) +" \ n "; # p            Rint "B:" +str (Isinstance (Val,type (self)) + "\ n"; New_node = NodeList (val) self._next = New_node Else:self._next.append (val) de            F __str__ (self): "" "," "Build standard string representation for list" "If Self._next = = None: Return "[" + str (self._value) + "]" else:rest_str = str (self._next) Rest_str = re St_str[1:] Return "[" + str (self._value) + "," + Rest_str def run_exampLe (): "" "Create Some Examples" "" Node_list = NodeList (2) print node_list sub_list = NodeList (5) #    Print "--------" Sub_list.append (6) # print "--------" sub_list2 = sub_list node_list.append (sub_list) Node_list.append (sub_list2) print node_list run_example ()

3Minimax

Https://class.coursera.org/principlescomputing-001/wiki/minimax
X and O alternate back and forth between Min and Max.
In X's term, try to maximize the score.
The O ' s term, try to minimize the score.



4 Mini Project Tic Tac Toe with Minimax

"" "" "" Mini-max tic-tac-toe Player "" "Import poc_ttt_guiimport poc_ttt_provided as provided# Set timeout, as Mini-max can take A long timeimport Codeskulptorcodeskulptor.set_timeout # scoring values-do not modifyscores = {provided. Playerx:1, provided. Draw:0, provided.    Playero: -1}def minimax (board, player): "" "Make a move through Minimax method. "" "Check_res = Board.check_win () if check_res! = None:return Scores[check_res], ( -1,-1) Else:em Pty_list = Board.get_empty_squares () Com_score =-2 Max_score = 2 Max_each = ( -1,-1) changed_ Player = Provided.switch_player (player) for each in Empty_list:cur_board = Board.clone () cur  _board.move (Each[0], each[1], player) Cur_score_tuple = Minimax (Cur_board, Changed_player) cur_score = Cur_score_tuple[0] If Cur_score * Scores[player] > com_score:com_score = cur_score * SCOR Es[player] #Used for Compare Max_score = Cur_score # used for return a value Max_each = each if Com_score = = 1:return Max_score, Max_each return Max_score, Max_each def mm_m        Ove (board, player): "" Make a move on the board.  Returns a tuple with a elements.     The first element is the score of the given board and the second element are the desired move as a tuple, (row, col).    "" "# print"-----------------new_move--------------"# print" B1: "+" player= "+str (player) +" \ n "# Print board#  Print "----------------" Score_and_board = Minimax (board, player) # print "C1" # Print score_and_board# Print "-----------------new_move--------------" return score_and_boarddef move_wrapper (board, Player, trials): "" "Wra    Pper to allow the use of the same infrastructure, is used for Monte Carlo tic-tac-toe. "" "Move = Mm_move (board, player) assert move[1]! = ( -1,-1)," ReTurned illegal move ( -1,-1) "Return move[1]# Test game with the console or the gui.# uncomment whichever Both should is commented out when you submit for# testing to save time. #test1 #mm_move (provided. Tttboard (3, False, [[provided]. Playerx, provided. EMPTY, provided. EMPTY], [provided. Playero, provided. Playero, provided. Playerx], [provided. Playero, provided. Playerx, provided. EMPTY]]), provided. Playerx) #mm_move (provided). Tttboard (3, False, [[provided]. Playerx, provided. Playero, provided. EMPTY], [provided. Playero, provided. Playero, provided. Playerx], [provided. Playero, provided. Playerx, provided. Playerx]]), provided. Playerx) #mm_move (provided). Tttboard (3, False, [[provided]. Playerx, provided. EMPTY, provided. Playerx], [provided. Playero, provided. Playero, provided. Playerx], [provided. Playero, provided. Playerx, provided. EMPTY]]), provided. Playero) #mm_move (provided). Tttboard (3, False, [[provided]. Playerx, provided. EMPTY, provided. EMPTY], [provided. Playero, provided. Playero, provided. Playerx], [provided. Playero, provided. Playerx, provided. Playerx]]), provided. Playero) #mm_move (provided). Tttboard (3, False, [[provided]. Playerx, provided. EMPTY, provided. EMPTY], [provided. Playero, provided. Playero, provided. Playerx], [provided. Playero, provided. Playerx, provided. EMPTY]]), provided. Playerx) #mm_move (provided). Tttboard (3, False, [[provided]. Playerx, provided. EMPTY, provided. EMPTY], [provided. Playero, provided. Playero, provided. EMPTY], [provided. EMPTY, provided. Playerx, provided. EMPTY]]), provided. Playerx) #mm_move (provided). Tttboard (2, False, [[provided]. EMPTY, provided. EMPTY], [provided. EMPTY, provided. EMPTY]]), provided. Playerx) #test1 #provided.play_game (Move_wrapper, 1, False) #poc_ttt_gui. Run_gui (3, provided. Playero, Move_wrapper, 1, False)

Note that the Minimax () method above has some simplified processing:

In Minimax, you need to alternate between maximizing and minimizing. Given the SCORES that we had provided you with, player X was always the maximizing player and play O are always the Minimiz ing player. You can use a If-else statement to decide if to maximize and when to minimize. But, can also is more clever by noticing so if you multiply the score by Scores[player] so you can always maximize

Suppose you want to use the IF else notation. Is this:

    Check_res = Board.check_win () if check_res! = None:return Scores[check_res], ( -1,-1) else:empty _list = Board.get_empty_squares () if player = = provided.            Playerx:max_score =-2;                Max_each = ( -1,-1) Changed_player = Provided.switch_player (player) for each in empty_list: cur_board= Board.clone () cur_board.move (each[0], each[1], player) Cur_score_tuple = mi                     Nimax (Cur_board, changed_player) Cur_score = cur_score_tuple[0] If Cur_score > Max_score: Max_score = Cur_score Max_each = each if Max_score = = Scores[provide D.playerx]: Return Max_score, Max_each return max_score, max_each elif player = = provided.            Playero:min_score = 2; Min_each = ( -1,-1) Changed_player = Provided.switch_player (player) for each in EMpty_list:cur_board= Board.clone () cur_board.move (each[0], each[1], player)                Cur_score_tuple = Minimax (Cur_board, changed_player) Cur_score = cur_score_tuple[0]                If Cur_score < Min_score:min_score = Cur_score Min_each = each if Min_score = = scores[provided. Playero]: Return Min_score, Min_each return Min_score, Min_each





Principle of Computing (Python) Learning notes (7) DFS Search + Tic Tac Toe use MiniMax stratedy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.