#coding=utf-8

def init_set():
r10=range(10)
return [(i, j, k, l)
for i in r10 for j in r10 for k in r10 for l in r10
if (i != j and i != k and i != l and j != k and j != l and k != l) ] #对给定的两组数,计算xAyB.不知道能不能更快些
def get_match_ab(target, source):
la, lb = 0, 0
for (i, t) in enumerate(target):
for (j, s) in enumerate(source):
if s == t:
if i == j:
la += 1
else:
lb += 1
#break this loop since we already found match
break
return (la, lb) #by lancer
#思路很好,把原来的16次比较变成了8次
#经过timeit验证确实速度有所提高
def get_match_ab2(target, source):
table = [-1] * 10
la, lb = 0, 0
for i in xrange(len(source)):
table[source[i]] = i
for i in xrange(len(target)):
if table[target[i]] == i:
la += 1
elif table[target[i]] != -1:
lb += 1
return (la, lb) #nums: the number_set list to be checked
#guess: last guess
#a, b: the number of aAbB
#@return: the rest number_sets which matche last guess
def check_and_remove(nums, guess, a, b):
rest_nums = []
for num_set in nums:
if (a, b) == get_match_ab(num_set, guess):
rest_nums.append(num_set)
return rest_nums #计算在nums中选择target以后,所有ab分支里面的剩余组合个数
def calc_ab_counts(target, nums):
#a * 10 + b is used to indicate an "a & b" combination
ab_map = {}
#init ab_map
abs = (0, 1, 2, 3, 4, 10, 11, 12, 13, 20, 21, 22, 30, 31, 40)
for ab in abs:
ab_map[ab] = 0
#let's do the calculation
for num_set in nums:
(a, b) = get_match_ab(num_set, target)
ab_map[a * 10 + b] += 1
return [ab_map[ab] for ab in abs] #计算一个选择相对于选择集的“标准差”
def calc_standard_deviation(target, nums):
ab_counts = calc_ab_counts(target, nums)
total = sum(ab_counts)
avg = float(total) / len(ab_counts)
sd = sum([(abc - avg)**2 for abc in ab_counts])
return sd #根据现有集合寻找下一个集合
#采用“最小标准差”作为衡量标准
def next_guess(nums):
min_sd = 0
min_set = ()
touched = False
for num_set in nums:
sd = calc_standard_deviation(num_set, nums)
if not touched or min_sd > sd:
touched = True
min_set = num_set
min_sd = sd
return min_set #根据现有集合寻找下一个集合
#随机选取,会有4-5个超过八次
def next_guess2(nums):
return nums[0] #折衷的方法:小于500用最小标准差
def next_guess3(nums):
if len(nums) > 500:
return大专栏  python猜数字游戏快速求解解决方案> next_guess2(nums)
else:
return next_guess(nums) #计算熵
import math
def calc_entropy(target, nums):
ab_counts = calc_ab_counts(target, nums)
total = sum(ab_counts)
hs = []
for abc in ab_counts:
h = 0
if abc:
p = float(abc) / total
h = p * math.log(p, 2)
hs.append(h)
return sum(hs) #使用信息量作为衡量标准
def next_guess4(nums):
min_sd = 0
min_set = ()
touched = False
for num_set in nums:
sd = calc_entropy(num_set, nums)
if not touched or min_sd > sd:
touched = True
min_set = num_set
min_sd = sd
return min_set def make_decision_tree():
from Queue import Queue
result = ((0, 1, 2, 3), {})
queue = Queue()
rest_nums = init_set()
queue.put((rest_nums, result))
#all xAyB set
abs = [(a, b) for a in range(5) for b in range(5 - a)] while not queue.empty():
(rest_nums, (guess, mapping)) = queue.get()
for (a, b) in abs:
new_rest_nums = check_and_remove(rest_nums, guess, a, b)
length = len(new_rest_nums)
if length == 1:
if a != 4: #b can't be other than 0 when a == 4
mapping[a * 10 + b] = new_rest_nums[0]
elif length > 1:
new_guess = next_guess4(new_rest_nums) #TODO: 替换guess函数调整算法
new_result = (new_guess, {})
mapping[a * 10 + b] = new_result
queue.put((new_rest_nums, new_result))
return result max_level = 0
level7_plus_tups = []
def pprint_result(result, level = 0):
global max_level, max_level_tup
(tup, mapping) = result
print tup
level += 1
if level > max_level:
max_level = level
if len(mapping) == 0:
print
else:
for key in mapping:
val = mapping[key]
#打印前缀
print u"%d|t" * level % tuple(range(1, level + 1)),
print u"%d:" % (level + 1),
#打印xAyB
print u"%dA%dB" % (key / 10, key % 10),
if len(val) == 4: #direct result
#打印结果
print val
if level >= 7:
level7_plus_tups.append((level, val))
else:
pprint_result(val, level) #来玩玩www.iplaypy.com
print u"Notice: 4A0B is NOT included, since it result to Game Over"
pprint_result(make_decision_tree())
print
print u"max level is:", max_level + 1
print u"level7 plus tuples:"
for (level, tup) in level7_plus_tups:
print u"level:", level + 1, u"ttup:", tup
print

python猜数字游戏快速求解解决方案的更多相关文章

  1. python猜数字游戏console版本

    加入python学习小组后的第一次作业,python GUI写猜数字游戏.由于加班比较多,第一步先实现console版本,下一步再实现GUI版本. 虽然猜数字游戏是个小游戏,但是涉及到的基础知识点还是 ...

  2. java & python猜数字游戏对比

    1.java版 package day03; import java.util.Random;import java.util.Scanner; /** * 猜数字游戏 * 随机生成一个1-100之间 ...

  3. python 猜数字游戏

    import random print('==============学无止境==========') secret=random.randint(1,10) print('sec:',secret) ...

  4. 猜数字游戏--基于python

    """题目:练习使用python写一个猜数字的游戏,数字范围0-100,每次猜错,需要给出缩小后的范围,每个人只有10次的猜测机会,猜测机会用完游戏结束!"&q ...

  5. python学习:猜数字游戏

    猜数字游戏   系统生成一个100以内的随机整数, 玩家有6次机会进行猜猜看,每次猜测都有反馈(猜大了,猜小了,猜对了-结束) 6次中,猜对了,玩家赢了. 否则系统赢了   #!/usr/bin/en ...

  6. Python实现猜数字游戏1.0版

    本文由荒原之梦原创,原文链接:http://zhaokaifeng.com/?p=702 """ 功能: 随机生成一个数字,最多有3次猜测机会,如果第一次没有猜对,则从第 ...

  7. [易学易懂系列|rustlang语言|零基础|快速入门|(23)|实战1:猜数字游戏]

    [易学易懂系列|rustlang语言|零基础|快速入门|(23)|实战1:猜数字游戏] 项目实战 实战1:猜数字游戏 我们今天来来开始简单的项目实战. 第一个简单项目是猜数字游戏. 简单来说,系统给了 ...

  8. 通过游戏学python 3.6 第一季 第九章 实例项目 猜数字游戏--核心代码--猜测次数--随机函数和屏蔽错误代码--优化代码及注释--简单账号密码登陆--账号的注册查询和密码的找回修改--锁定账号--锁定次数--菜单功能'menufile

      通过游戏学python 3.6 第一季 第九章 实例项目 猜数字游戏--核心代码--猜测次数--随机函数和屏蔽错误代码--优化代码及注释--简单账号密码登陆--账号的注册查询和密码的找回修改--锁 ...

  9. 通过游戏学python 3.6 第一季 第八章 实例项目 猜数字游戏--核心代码--猜测次数--随机函数和屏蔽错误代码--优化代码及注释--简单账号密码登陆--账号的注册查询和密码的找回修改--锁定账号--锁定次数

    通过游戏学python 3.6 第一季 第八章 实例项目 猜数字游戏--核心代码--猜测次数--随机函数和屏蔽错误代码--优化代码及注释--简单账号密码登陆--账号的注册查询和密码的找回修改--锁定账 ...

随机推荐

  1. long型长整数字在前端页面显示异常及其解决方法

    文章目录 1.引子 2.解决问题 (1)初试EL表达式取long型数值 (2)再探EL表达式取字符串格式long型数值 (3)最后一试---给EL表达式加引号 3.总结 1.引子 在做项目中,发现了一 ...

  2. 数组,字符串方法总结 Unicode 数字

    String.prototype.charCodeAt(index) 就是返回字符串中下标单个数值  对应的编码表的10进制表示数值 方法返回0到65535之间的整数,表示给定索引处的UTF-16代码 ...

  3. JSON字符串

    原因:由于之前接触的JSON都是字符串与数组之间的转化,思维定式认为JSON只是字符串与数组的转化 这个原因是错误的 首先 JSON 是一种语法,用来序列化对象.数组.数值.字符串.布尔值和 null ...

  4. JavaSE--[转]加密和签名的区别

    转载 http://blog.csdn.net/u012467492/article/details/52034835 私钥用来签名的,公钥用来验签的.公钥加密私钥解密是秘送,私钥加密公钥解密是签名 ...

  5. JavaSE--异常信息打印

    最近项目用到第三方jar包,抛出运行时异常,打在日志用的 方法.得到的错误描述并不详尽,遂想到平时用的 发现其可以重定向输出,平时用流多是和文件相关,但是在当前背景下用文件打开流显得不是很合适,翻了下 ...

  6. centos快速安装mysql

    1. wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm 2. rpm -ivh mysql-community-r ...

  7. 如何查看iOS系统版本在iPhone设备上的占有率

    我们平时开发的时候有时要考虑到系统的兼容版本,但是怎么知道各个版本的系统占有率,其实这个苹果官方是有提供的.进入如下链接到的页面就可以知道各大系统版本的占有率了,不过说实在的iPhone用户的系统更新 ...

  8. log4j中%5p的含义

    因为日志级别分别有error,warn,info,debug,fatal5种,有些是5个字母的,有些是4个字母的,如果直接写%p就会对不齐,%-5p的意思是日志级别输出左对齐,右边以空格填充,%5p的 ...

  9. servletHomeWork

    2. http全称是什么? 超文本传输协议(HTTP, HyperText Transfer Protocol)是互联网上应用为最广泛的一种网络协议. 3.http协议是无状态的协议是什么意思?请说明 ...

  10. Exception in thread "main" java.lang.AbstractMethodError

    参考https://stackoverflow.com/questions/15758151/class-conflict-when-starting-up-java-project-classmet ...