第一步:每一次生成1、0、0,一组3个随机数,表示3个门。注意,是1、0、0三个数的排列组合。
(就是用0代表兔子,1代表车,有两个0,1个1)
第二步:生成一个随机数,1-3之间的,表示选手第一次开了哪个门。
第三步:如果开了有车的门,记录为"选手第一次开门就获得大奖”
如果开了没车的门,进入第四步
第四步:生成一个随机数,表示主持人在剩下的两扇门里开了一扇。
如果主持人开了有车的门,记录为“主持人打开了有车的门,选手获奖”
如果主持人开了没车的门,记录为“主持人打开了没车的门,选手没获奖”
第五步:生成一个随机数,表示选手是否改换门。
不管选手换没换门,记录:“选手换门,获得大奖”
或者“选手未换门,获得大奖”
将结果写入到csv文件
import random
import csv
import codecs
import re
from random import choice
def createDoor():
'''
随机生成门内的车或兔子
:return:door_list
'''
door_list = [0, 0, 0]
door = random.randint(0,2)
door_list[door] = 1 # 向门内放入车,剩下的值为0 代表兔子
return door_list # 将随机生成的包含兔子和车的门返回
def choiceDoor(doors):
user_first_choice = random.randint(0,2)
if doors[user_first_choice] == 1 :
print("选手第一次开门就获得大奖")
# return user_first_choice,None,None
return 1,0,0
else:
doors.remove(doors[user_first_choice])
host_first_choice = choice(doors)
if doors[host_first_choice] == 1:
print("主持人第一次开门就获得大奖")
# return user_first_choice,host_first_choice,None
return 0,1,0
else :
print("主持人第一次开门就没奖")
change_door = random.randint(0,1)
if change_door == 1:
print("用户换门,获奖")
# return user_first_choice, host_first_choice,change_door
return 0,0,1
else:
print("用户不换门没奖")
# return user_first_choice, host_first_choice, change_door
return 0,0,0
def computationalProbability(total,all_choice):
# print(all_choice)
choice_one = 0
choice_two = 0
choice_three = 0
# for i in range(len(all_choice)):
for choice in all_choice:
# print(choice)
# print(choice[0],choice[1],choice[2])
choice_one = choice_one + choice[0]
# print(choice_one)
choice_two = choice_two + choice[1]
# print(choice_two)
choice_three = choice_three + choice[2]
# print(choice_three)
one = choice_one/total
two = choice_two/total
three = choice_three/total
chage = [choice_one,choice_two,choice_three]
reuslt = [one,two,three]
return chage,reuslt
def writefile(filename,change,result):
with codecs.open(filename,'a','utf8') as csvfile:
filenames = [" ","用户第一次选择和获奖概率", "主持人第一次选择和概率", "换门和概率"]
writer = csv.DictWriter(csvfile,fieldnames=filenames)
writer.writeheader()
writer.writerow({" ":"总次数","用户第一次选择和获奖概率":change[0],"主持人第一次选择和概率":change[1],"换门和概率":change[2]})
writer.writerow({" ":"概率","用户第一次选择和获奖概率":result[0],"主持人第一次选择和概率":result[1],"换门和概率":result[2],})
def main():
# while True:
total = 10000
filename = "test.csv"
all_choice = []
for i in range(total):
doors = createDoor()
user_first_choice, host_first_choice, change_door =choiceDoor(doors)
singal_choice = [user_first_choice, host_first_choice, change_door]
print(singal_choice)
print("*"*100)
all_choice.append(singal_choice)
# print(all_choice)
change,result = computationalProbability(total, all_choice)
writefile(filename,change,result)
if __name__ == '__main__':
main()