zoukankan      html  css  js  c++  java
  • python学习--程序设计方法实例一

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    #matchSim.py
    from random import * 
     
    def main():
        printIntro()
        probA,probB,n = getInputs()
        winsA, winsB = simNGames(n,probA,probB)
        PrintSummary(winsA, winsB)
     
    def printIntro():
        print('本程序可模拟两个运动员之间的比赛结果')
        print('假设有两个运动员甲和乙')
        print('以往获胜概率如下:(0到1之间的数字)')
     
    def getInputs():
        a = eval(input('运动员甲获胜的概率是?'))
        b = eval(input('运动员乙获胜的概率是?'))
        n = eval(input('模拟他们之间比赛的场次?'))
        return a,b,n
     
    def simNGames(n,probA,probB):
        winsA = 0
        winsB = 0
        for i in range(n):
            scoreA,scoreB = simOneGame(probA,probB)
            if scoreA >scoreB:
                winsA = winsA + 1
            else:
                winsB = winsB + 1
        return winsA,winsB
    def simOneGame(probA,probB):  #一场比赛的结果预测
        '''
        假设发球权在甲手时,获得的随机数小于甲的获胜概率,则甲得分加一分,甲继续发球,
        如果获得的随机数大于甲时,甲不得分,甲把发球权交换给乙;
        假设乙获得发球权后,获得的随机数小于乙的获胜概率,则乙得分加一分,乙继续发球,
        如果获得的随机数大于乙时,乙不得分,乙把发球权交换给甲。
        然后返回甲乙的分数
        '''
        scoreA = 0
        scoreB = 0
        serving = ""
        while not gameOver(scoreA,scoreB): #哪个先到15分一场比赛结束
            if serving == "":        
                if random() < probA:  #random()函数每次获取0到1之间的随机数
                    scoreA = scoreA + 1
                else:
                    serving = ""
            else:
                if random() < probB:
                    scoreB = scoreB + 1
                else:
                    serving = ""
        return scoreA,scoreB
     
    def gameOver(a,b):
        return a==15 or b==15
     
    def PrintSummary(winsA, winsB):
        n = winsA + winsB
        print('
    比赛模拟:%d'%n)
        print('甲获胜场次:{0}({1:0.1%})'.format(winsA,winsA/n))
        print('乙获胜场次:{0}({1:0.1%})'.format(winsB,winsB/n))
     
    if __name__ == '__main__':
        main()
  • 相关阅读:
    解决VS控制台窗口自动关闭问题
    ZOJ1003:Crashing Balloon(dfs)
    POJ2607:Fire Station(SPFA+枚举)
    C语言在屏幕上输出玫瑰花图片
    HRBUST
    UVA10182: Bee Maja (模拟)
    洛谷P1144: 最短路计数(bfs)
    (转载)MySQL LIKE 用法:搜索匹配字段中的指定内容
    (转载)[MySQL技巧]INSERT INTO… ON DUPLICATE KEY UPDATE
    (转载)INSERT INTO .. ON DUPLICATE KEY 语法与实例教程
  • 原文地址:https://www.cnblogs.com/hayden1106/p/7843065.html
Copyright © 2011-2022 走看看