Principle of Computing (Python)學習筆記(7) DFS Search + Tic Tac Toe use MiniMax Stratedy

1. Trees

Tree is a recursive structure.

1.1 math nodes ?

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

page=trees

1.2 CODE無parent域的樹 ? ??

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

class Tree:"""Recursive definition for trees plus various tree methods"""def __init__(self, value, children):"""Create a tree whose root has specific value (a string)Children is a list of references to the roots of the subtrees.  """self._value = valueself._children = childrendef __str__(self):"""Generate a string representation of the treeUse an pre-order traversal of the tree"""ans = "["ans += str(self._value)for child in self._children:ans += ", "ans += str(child)return ans + "]"def get_value(self):"""Getter for node's value"""return self._valuedef children(self):"""Generator to return children"""for child in self._children:yield childdef num_nodes(self):"""Compute number of nodes in the tree"""ans = 1for child in self._children:ans += child.num_nodes()return ansdef num_leaves(self):"""Count number of leaves in tree"""if len(self._children) == 0:return 1ans = 0for child in self._children:ans += child.num_leaves()return ansdef height(self):"""Compute height of a tree rooted by self"""height = 0for child in self._children:height = max(height, child.height() + 1)return heightdef 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_aprint "Tree consisting of single leaf node labelled 'b'", tree_btree_cab = Tree("c", [tree_a, tree_b])print "Tree consisting of three node", tree_cabtree_dcabe = Tree("d", [tree_cab, Tree("e", [])])print "Tree consisting of five nodes", tree_dcabeprint 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_treeprint "The tree has", my_tree.num_nodes(), "nodes,", print my_tree.num_leaves(), "leaves and height",print my_tree.height()#import poc_draw_tree#poc_draw_tree.TreeDisplay(my_tree)#run_examples()


1.3 CODE有parent域的樹?

?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 list of references to the roots of the children.  parent (if specified) is a reference to the tree's parent node"""poc_tree.Tree.__init__(self, value, children)self._parent = parentfor child in self._children:child._parent = self          def set_parent(self, parent):"""Update parent field"""self._parent = parentdef 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"""passdef run_examples():"""Create some trees and apply various methods to these 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_dcabeprint "This is tree that contains b -", tree_b.get_root()import poc_draw_treepoc_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 is tree that contains b - [d, [c, [a], [b]], [e]]
#The node b has depth 2
#The node e has depth 1

1.4 CODE arithmetic expreesion由樹來表達

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

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

# import Tree class definition
import 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 ArithmeticExpression(poc_tree.Tree):"""Basic operations on arithmetic expressions"""def __init__(self, value, children, parent = None):"""Create an arithmetic expression as a tree"""poc_tree.Tree.__init__(self, value, children)def __str__(self):"""Generate a string representation 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 ansdef 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 = ArithmeticExpression("1", [])two = ArithmeticExpression("2", [])three = ArithmeticExpression("3", [])print oneprint one.evaluate()one_plus_two = ArithmeticExpression("+", [one, two])print one_plus_twoprint one_plus_two.evaluate()one_plus_two_times_three = ArithmeticExpression("*", [one_plus_two, three])print one_plus_two_times_threeimport poc_draw_treepoc_draw_tree.TreeDisplay(one_plus_two_times_three)print one_plus_two_times_three.evaluate()run_example()

2 List


In Python, lists are primarily iterative data structures that are processed using loops. However, in other languages such as Lisp and Scheme, lists are treated primarily as recursive data structures and processed 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 = valself._next = Nonedef append(self, val):"""Append a node to an existing list of nodes"""
#        print "---------called---append()--------\n"if self._next == None:
#            print "A:"+str(isinstance(val,int))+"\n";
#            print "B:"+str(isinstance(val,type(self)))+"\n";new_node = NodeList(val)self._next = new_nodeelse:self._next.append(val)def __str__(self):"""Build standard string representation for list"""if self._next == None:return "[" + str(self._value) + "]"else:rest_str = str(self._next)rest_str = rest_str[1 :]return "[" + str(self._value) + ", " + rest_strdef run_example():"""Create some examples"""node_list = NodeList(2)print node_listsub_list = NodeList(5)
#    print "--------"sub_list.append(6)
#    print "--------"    sub_list2 = sub_listnode_list.append(sub_list)node_list.append(sub_list2)print node_listrun_example()

3?Minimax

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_gui
import poc_ttt_provided as provided# Set timeout, as mini-max can take a long time
import codeskulptor
codeskulptor.set_timeout(60)# SCORING VALUES - DO NOT MODIFY
SCORES = {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:empty_list = board.get_empty_squares()com_score = -2max_score = -2max_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 * SCORES[player] # used for comparemax_score = cur_score  # used for return a valuemax_each = eachif com_score == 1:return max_score, max_each            return max_score, max_each       def mm_move(board, player):"""Make a move on the board.Returns a tuple with two elements.  The first element is the scoreof the given board and the second element is the desired move as atuple, (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):"""Wrapper to allow the use of the same infrastructure that was usedfor 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 you prefer.
# Both should be 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)

注意上面的minimax()方法進行了一些簡化處理:

In Minimax, you need to alternate between maximizing and minimizing. Given the SCORES that we have provided you with, player X is always the maximizing player and play O is always the minimizing player. You can use an if-else statement to decide when to maximize and when to minimize. But, you can also be more clever by noticing that if you multiply the score by SCORES[player] then you can always maximize

假設要用if else的寫法。是這種:

    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 = minimax(cur_board, changed_player)cur_score = cur_score_tuple[0]if cur_score > max_score:max_score = cur_scoremax_each = eachif max_score == SCORES[provided.PLAYERX]:return max_score, max_eachreturn 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_scoremin_each = eachif min_score == SCORES[provided.PLAYERO]:return min_score, min_eachreturn min_score, min_each





轉載于:https://www.cnblogs.com/zsychanpin/p/6812461.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/455761.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/455761.shtml
英文地址,請注明出處:http://en.pswp.cn/news/455761.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C#線程篇---Task(任務)和線程池不得不說的秘密

我們要知道的是&#xff0c;QueueUserWorkItem這個技術存在許多限制。其中最大的問題是沒有一個內建的機制讓你知道操作在什么時候完成&#xff0c;也沒有一個機制在操作完成是獲得一個返回值&#xff0c;這些問題使得我們都不敢啟用這個技術。 Microsoft為了克服這些限制&…

關于編譯FFMPEG的初級教程

關于編譯FFMPEG的初級教程1.首先我們要下載相關工具&#xff0c;這里不多說&#xff0c;大家按照我的地址去下載文件就好了 MINGW下載地址&#xff1a;http://prdownloads.sourceforge.net/mingw/MinGW-3.1.0-1.exe?download 然后在下載MSYS &#xff1a;http://prdownloads.…

電子科學與技術相關索引匯總

電子科學與技術相關索引匯總 關于安裝deepinwindow10雙系統有時沒有聲音的問題關于deepin系統安裝design compiler的問題解答基于51單片機的交通燈控制設計基于物聯網的智能垃圾桶設計基于FPGA 的8b10b編解碼電路前端電路設計金屬磁記憶傳感器封裝集成電路版圖與工藝課程設計之…

【百度面試】閘機測試場景

面試被問到這一題思路想法&#xff1a; 自己找了相關內容充實自我。內容分享如下&#xff1a; 隨著人臉識別技術的成熟&#xff0c;閘機行業大量應用人臉識別算法&#xff0c;只因現今的人臉識別算法也已經能夠保證識別率、識別速度、誤識率和拒識率等各項指標的優異性&#x…

前后端分離項目如何部署_前后端分離項目,如何解決跨域問題?

跨域資源共享(CORS)是前后端分離項目很常見的問題&#xff0c;本文主要介紹當SpringBoot應用整合SpringSecurity以后如何解決該問題。01 什么是跨域問題&#xff1f;CORS全稱Cross-Origin Resource Sharing&#xff0c;意為跨域資源共享。當一個資源去訪問另一個不同域名或者同…

使用模板引擎artTemplate的幾個問題總結

一、Template not found 有的時候模板寫的并沒有問題&#xff0c;可就是找不到。這時候可能是<script>加載順序問題&#xff0c;模板渲染在模板加載完成之前先執行了&#xff0c;調整<script>的順序。 二、模板中將字符串轉化成數字 利用html中的表單來轉化&#x…

Android報“android.content.res.Resources$NotFoundException: String resource ID #0x2”錯誤

Android報“android.content.res.Resources$NotFoundException: String resource ID #0x2”錯誤 當調用setText()方法時如果傳入int型是不會被當成內容而是resourceID來使用&#xff01; 所以報錯&#xff01; 解決方法&#xff1a;TextView.setText("" arg) 轉為St…

時間戳問題匯總

大家好 我剛接觸流媒體不久&#xff0c; 現在遇到一個非常奇怪的問題&#xff0c;向各位大俠請假&#xff0c;請你們指點。 問題是這樣的 用一個 VLC(流媒體客戶端) 去請求流媒體服務器上的數據&#xff0c; 但是獲得的數據播放速度明顯快于1倍速&#xff0c;大概是 timest…

如何實現 C/C++ 與 Python 的通信?

如何實現 C/C 與 Python 的通信&#xff1f; 想在 C 中用 Python 進行數值計算&#xff0c;Python 需要訪問 C 的變量并計算后返回數值。有什么好辦法呢&#xff1f; 參考https://www.zhihu.com/question/23003213

前端相關索引匯總

前端相關索引匯總 HTML相關 HTML概述和基本結構HTML中Head頭HTML標題 HTML段落,換行,字符實體HTML塊,含樣式的標簽HTML中的圖片HTML中的鏈接HTML中的列表HTML中的表格HTML中的表單 CSS相關 Css基本語法及頁面引用Css中的選擇器Css顏色和文本字體CSS邊框,背景,邊距,溢出CSS中的…

nginx反向代理配置 多個_實例分享:Nginx學習之反向代理WebSocket配置實例

寫在開始去年&#xff0c;做過一款競賽打分的APP。具體需求&#xff0c;同組教師之間可以相互通信&#xff0c;及時通知同組人員&#xff0c;其他組員做了那些操作(當然&#xff0c;這只是針對特定操作)。實現方案采用目前比較成熟的WebSocket技術&#xff0c;WebSocket協議為創…

性能測試總結(一)---基礎理論篇

隨著軟件行業的快速發展&#xff0c;現代的軟件系統越來越復雜&#xff0c;功能越來越多&#xff0c;測試人員除了需要保證基本的功能測試質量&#xff0c;性能也隨越來越受到人們的關注。但是一提到性能測試&#xff0c;很多人就直接連想到Loadrunner。認為LR就等于性能測試&a…

Makefile 7——自動生成依賴關系 三顆星

后面會介紹gcc獲得源文件依賴的方法&#xff0c;gcc這個功能就是為make而存在的。我們采用gcc的-MM選項結合sed命令。使用sed進行替換的目的是為了在目標名前加上“objs/”前綴。gcc的-E選項&#xff0c;預處理。在生成依賴關系時&#xff0c;其實并不需要gcc編譯源文件&#x…

JavaScript使用場景

JavaScript嵌入頁面的方式 1、行間事件&#xff08;主要用于事件&#xff09; <input type"button" name"" onclick"alert(ok&#xff01;);">2、頁面script標簽嵌入 <script type"text/javascript">var a 你好&#…

集合添加元素python_Python 集合(Set)

Python 集合&#xff08;Set&#xff09; 在本文中&#xff0c;您將學習關于Python集的所有內容;如何創建它們、添加或刪除其中的元素&#xff0c;以及在Python中對集合執行的所有操作。 Python中的集合是什么&#xff1f; 集合是項目的無序集合。每個元素都是唯一的&#xff0…

一個極其高效的虛擬機內存冗余消除機制:UKSM

Linux內核機制KSM(Kernel Samepage Merging)能合并KVM虛擬機之間相同內存的頁面&#xff0c;被CentOS, RHEL之類的服務器內核廣泛采用&#xff0c;但是其速度很慢。UKSM(Ultra KSM)是國人在此基礎上的極大改進。通過使用了更高級的算法&#xff0c;UKSM的新特性包括&#xff1a…

【分享】 codeReview 的重要性

研發都知道代碼 Review 的重要性&#xff0c;在代碼 Review 也越來越受大家重視&#xff0c;我參與了大量的代碼 Review&#xff0c;明顯地感受到有效的代碼 Review 不但能提高代碼的質量&#xff0c;更能促進團隊溝通協作&#xff0c;建立更高的工程質量標準&#xff0c;無論對…

FFMPEG功能

FFMPEG功能1&#xff0e; 視頻音頻格式轉換Ffmpeg能使用任何支持的格式和協議作為輸入&#xff1a;*比如你可以輸入YUV文件&#xff1a;ffmpeg -i /tmp/test%d.Y /tmp/out.mpg 它將要使用如下文件&#xff1a; /tmp/test0.Y, /tmp/test0.U, /tmp/test0.V,/tmp/test1.Y, /tmp…

線程02

2019獨角獸企業重金招聘Python工程師標準>>> 線程中有幾個方法需要我們區分 1 sleep方法是表示線程執行到這的時候只是暫時處于“睡眠”狀態&#xff0c;在這種狀態下線程是不會釋放CPU資源的&#xff0c;當到達休眠時間后&#xff0c;線程繼續“起來”干活。當線程…