用Python分析石头剪刀布中的概率问题
2021-09-20_NebulaChien的博客-CSDN博客
两个人用猜拳的方式决定胜负,所有出拳的组合有3x3=9种,其中A胜、B胜和平局的组合各有三种,也就是说每一种结局对应的概率为1/3,那么这个过程到底是如何是实现的呢?下面我们用Python模拟这一过程。
代码如下,用到列表索引 、random库 #Possiblity of mora game from random import * mora_GamerA=["Rock","Paper","Scissor"] mora_GamerB=["Rock","Paper","Scissor"] count_A_win=0.0 count_B_win=0.0 count_Draw=0.0 Flag=1 while Flag: round=int(input("Enetr rounds:(rounds>=10)")) """ use while of if to make sure their is correct index for range """ if round<10: print("The input bureau does not meet the requirements") Flag=0 break else: for round in range(1,round+1): print("Game round {}".format(round)) guess_A=mora_GamerA[randint(0,2)] guess_B=mora_GamerB[randint(0,2)] """ Attention the range of list index """ if (guess_A=="Rock" and guess_B=="Scissor") or (guess_A=="Paper" and guess_B=="Rock") or (guess_A=="Scissor" and guess_B=="Paper"): count_A_win+=1 print("A is {},B is {}".format(guess_A,guess_B)) print("Gamer A is winner") elif guess_A==guess_B: count_Draw+=1 print("A and B is {}".format(guess_A)) print("Draw") else: count_B_win+=1 print("A is {},B is {}".format(guess_A,guess_B)) print("Gamer B is winner") print("In {} rounds,gamer A have won {} rounds and gamer B have won {} rounds,{} rounds is draw.".format(round,count_A_win,count_B_win,count_Draw)) print("The possiblity of A win is {}".format(count_A_win/round)) print("The possiblity of B win is {}".format(count_B_win/round)) print("The possiblity of draw is {}".format(count_Draw/round)) Flag=int(input("Enter 1 to continue and 0 to exit :")) if Flag!=1 and Flag!=0: Flag=0 print("Force exit because mistake input")
可以看到,并不是每次输入一个rounds都对应1/3的结果,因为1/3是理想条件下根据大量实验统计得到的,而随着rounds逐渐增大,乃至于大于1000000,得出的结果会越来越逼近0.333333...
emmmm,其实写这段代码是放假无聊找点事做,因为计二报的是Python,虽然有比较强的基础,但还是看看书,顺带熟悉一下各种库的用法,random库是真的蛮有意思。
第一次在文章里面嵌入代码不太熟练,缩进什么的都惨不忍睹[捂脸]
各位小伙伴将就一下[谢谢]
目前大二,物联网专业,以后有空会分享一些有趣的学习成果,大家有什么想了解的也可以打在评论区,算法、硬件、专业等等,如有不严谨之处,求求某位大佬出来教我做事[流泪]
祝各位同学,各位大佬中秋节快乐![比心]