Python programming method

Python programming ideas
1. Top-down design
2. Bottom-up execution
Example : sports code

1. top-down design

#Games.py

from random import random
def printIntro():
    print("模拟两个选手A和B的某种竞技比赛")
    print("程序运行需要A和B的能力值(0~1之间的小数表示)")

def getInputs():
    a=eval(input("请输入选手A的能力值:"))
    b=eval(input("请输入选手B的能力值:"))
    n=eval(input("模拟比赛的场次数量:"))
    return a,b,n

def simNGames(n,probA,probB):
    winsA,winsB=0,0
    for i in range(n):
        scoreA,scoreB=simoneGame(probA,probB)
        if scoreA>scoreB:
            winsA+=1
        else:
            winsB+=1
    return winsA,winsB

def gameover(a,b):
    return a==15 or b==15

def simoneGame(probA,probB):
    scoreA,scoreB=0,0
    serving="A"
    while not gameover(scoreA,scoreB):
        if serving=='A':
            if random()<probA:
                scoreA+=1
            else:
                serving="B"
        else:
            if random()<probB:
                scoreB+=1
            else:
                serving="A"
    return scoreA,scoreB

def printSummary(winA,winB):
    n=winA+winB
    print("共模拟{}场比赛".format(n))
    print("A赢得的比赛场数为{},占比{:0.1%}".format(winA,winA/n))
    print("B赢得的比赛场数为{},占比{:0.1%}".format(winB,winB/n))

def main():
    printIntro()
    proA,proB,n=getInputs()
    winsA,winsB=simNGames(n,proA,proB)
    printSummary(winsA,winsB)

main()

2. Bottom-Up Execution The best way to
execute a medium-sized program is to start at the bottom of the diagram and work your way up. Or run and test each basic function first, and then test the overall function composed of basic functions, which helps to locate errors.

The Python interpreter provides import reserved words to assist in the development of test units. The syntax is as follows:
import <source file name>

Note that the source file name cannot contain a period (.)

For example, to unit test the gameover() function of the above code, the code is as follows:

>>>import Games
>>>Games.gameover(15,10)
True

When using spyder, just type gameover(15,10) directly in ipython, for example:

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325474892&siteId=291194637