玩蛇网提供最新Python编程技术信息以及Python资源下载!

益智盒子问题python的解决方法

python 培训

益智盒子问题python的解决方法,也可以叫罪犯与盒子的问题。

import sys  
import random  

def strategy(boxes, p):  
    ''''' return True if strategy success '''  
    return False  

def simulate(n, strategy, times):  
    ''''' n: number of boxes or prisoners
        strategy: strategy used 
        times: random simulation times 
        return numbers of succeeded prisoners as list 
        www.iplaypython.com
    '''  
    boxes = range(n)  
    result = []  

    for i in xrange(times):  
        random.shuffle(boxes)  
        success = 0  
        for p in xrange(n):  
            if strategy(boxes, p):  
                success += 1  
        result.append(success)  

    return result  

def standard_strategy(boxes,p):
    times_remain = len(boxes)/2
    current = p

    while times_remain > 0:
        times_remain -=1
        if boxes[current] ==p:
            return True
        else:
            current = boxes[current]

    return False

n = 100
result = simulate(n,standard_strategy,100)

print result

import matplotlib.pyplot as plt

dist = [result.count(i) for i in range(n+2)]

plt.bar(range(n+2),dist)

plt.show()

玩蛇网原创,转载请注明文章出处和来源网址:http://www.iplaypython.com/code/game/g2444.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网Python新手QQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
文章发布日期:2016-04-11 09:25 玩蛇网 www.iplaypython.com

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
相关文章推荐
别人正在看
特别推荐
去顶部去底部