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()

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.mzph.cn/news/455761.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C#线程篇---Task(任务)和线程池不得不说的秘密

我们要知道的是&#xff0c;QueueUserWorkItem这个技术存在许多限制。其中最大的问题是没有一个内建的机制让你知道操作在什么时候完成&#xff0c;也没有一个机制在操作完成是获得一个返回值&#xff0c;这些问题使得我们都不敢启用这个技术。 Microsoft为了克服这些限制&…

【百度面试】闸机测试场景

面试被问到这一题思路想法&#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…

时间戳问题汇总

大家好 我刚接触流媒体不久&#xff0c; 现在遇到一个非常奇怪的问题&#xff0c;向各位大侠请假&#xff0c;请你们指点。 问题是这样的 用一个 VLC(流媒体客户端) 去请求流媒体服务器上的数据&#xff0c; 但是获得的数据播放速度明显快于1倍速&#xff0c;大概是 timest…

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…

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

Python 集合&#xff08;Set&#xff09; 在本文中&#xff0c;您将学习关于Python集的所有内容;如何创建它们、添加或删除其中的元素&#xff0c;以及在Python中对集合执行的所有操作。 Python中的集合是什么&#xff1f; 集合是项目的无序集合。每个元素都是唯一的&#xff0…

【分享】 codeReview 的重要性

研发都知道代码 Review 的重要性&#xff0c;在代码 Review 也越来越受大家重视&#xff0c;我参与了大量的代码 Review&#xff0c;明显地感受到有效的代码 Review 不但能提高代码的质量&#xff0c;更能促进团队沟通协作&#xff0c;建立更高的工程质量标准&#xff0c;无论对…

线程02

2019独角兽企业重金招聘Python工程师标准>>> 线程中有几个方法需要我们区分 1 sleep方法是表示线程执行到这的时候只是暂时处于“睡眠”状态&#xff0c;在这种状态下线程是不会释放CPU资源的&#xff0c;当到达休眠时间后&#xff0c;线程继续“起来”干活。当线程…

@postconstruct注解方法没有执行_把对象的创建交给spring来管理(注解IOC)

自动按照类型注入/** * 账户的业务层实现类 * * 曾经XML的配置&#xff1a; * <bean id"accountService" class"com.itheima.service.impl.AccountServiceImpl" * scope"" init-method"" destroy-method""> * <pro…

Kubernetes初步学习

今天分享如题&#xff1a; Kubernetes 本篇内容源于工作项目需要自学 但K8s确实现在十分的主流so推荐给大家 最近更新缓慢由于工作太忙惹&#xff0c;忙里偷闲整理愿分享能与君共勉&#x1f4aa; 大家新年快乐&#x1f389; &#x1f508;言归正题&#xff0c;相信很多朋友…

CABAC编码

H&#xff0e;264&#xff0f;AVC标准采用了很多新技术和新方法&#xff0c;大大提高了视频编码效率&#xff0c;其中CABAC便是H&#xff0e;264&#xff0f;AVC采用的新型熵编码方法之一。CABAC采用了高效的算术编码思想&#xff0c;同时充分考虑了视频流相关统计特性&#xf…

【教程分享】Jmeter入门教程

好&#xff01;回归学长每周的教程分享&#xff01; PART2 >今天又来分享Jmter 因为最近好像有相关工作内容 提前准备资修一下 分享仅供参考- JMeter的作用对软件做压力测试 1.能够对HTTP和FTP服务器进行压力和性能测试&#xff0c; 也可以对任何数据库进行同样的测试&…

快速傅里叶变换python_FFT快速傅里叶变换的python实现过程解析

FFT是DFT的高效算法&#xff0c;能够将时域信号转化到频域上&#xff0c;下面记录下一段用python实现的FFT代码。 # encodingutf-8 import numpy as np import pylab as pl # 导入和matplotlib同时安装的作图库pylab sampling_rate 8000 # 采样频率8000Hz fft_size 512 # 采样…

rabbitmq的安装全过程

2019独角兽企业重金招聘Python工程师标准>>> 1 首先下载安装依赖elang 添加yum支持 cd /usr/local/src/ mkdir rabbitmq cd rabbitmq wget http://packages.erlang-solutions.com/erlang-solutions-1.0-1.noarch.rpm rpm -Uvh erlang-solutions-1.0-1.noarch.rpm rp…

【框架学习分享】HttpRunner

今天文章分为两部分 :) PART1 HttpRunner内容分享/ PART2 关于后厂村儿 10 Minutes HttpRunner: PART 1 首先感谢作者开源&#x1f44d; 因为最近工作需要用到HttpRunner&#xff0c; 于是便趁着周末学了下这个测试框架&#xff0c;感觉还可以~ 所以分享一下今天的学习记…

python报名_2019年少儿Python创意编程比赛报名时间

2019年Python创意编程比赛时间及相关规定&#xff1a;参赛对象 Python创意编程比赛设初中组和高中组。 全国各地初中、高中(含中等职业学校)在校学生均以个人名义报名参加。 参赛步骤 Python创意编程比赛分初评、复评和终评三个阶段&#xff0c;初评和复评以线上形式开展&#…