夜光带你走进python开发 (四十)传奇语言

夜光序言:

繁华落幕 山河永寂

终换不回 你我情谊

愿以此情 了却红尘

咫尺天涯 天各一人

就此绝笔 铭记绝恋

但愿来世 再不相见

 

 

正文:自顶向下的设计 

 

顶层设计(第一阶段)举例 


 步骤1:打印程序的介绍性信息 
                 printIntro() 
 步骤2:获得程序运行所需的参数:ProA、ProB、n 
                 probA,probB,n = getInputs() 


 步骤3:模拟n次比赛 
        winsA, winsB = simNGames(n,probA,probB) 
 步骤4:输出球员A和B获胜比赛的次数和概率 
        printSummary(winsA, sinsB) 


def main(): 
          printIntro() 
 probA,probB,n = getInputs()  
 winsA, winsB = simNGames(n,probA,probB) 
 PrintSummary(winsA, sinsB) 

 

第一阶段 
 

第二阶段 

 

第二阶段 


 PrintIntro()函数; 
   def printIntro(): 
         print(‘This program simulates a game between two’) 
         print(‘There are two players, A and B’)           
         print(‘Probability(a number between 0 and 1)is used’)


 getInputs()函数; 
     def getInputs(): 
          a = eval(input(‘What is the prob.player A wins?’)) 
          b = eval(input(‘What is the prob.player B wins?’))      
          n = eval(input(‘How many games to simulate?’)) 
          return a,b,n 


 simNGames()函数(核心)     

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 

第三阶段 

# 夜光:simOneGame()函数;     
def simOneGame(probA,probB):           
scoreA = 0           
scoreB = 0           
serving = 'A'           
while <condition>:              
<todo>  
# 夜光:第三阶段 simOneGame()函数完整代码:     
def simOneGame(probA,probB):            
scoreA = 0            
scoreB = 0            
serving = "A"            
while not gameOver(scoreA,scoreB):                  
if serviong == "A":                        
if random() < probA:                              
scoreA = scoreA + 1                        
else:                              
serving = "B"                 
else:                       
if random() < probB:                          
scoreB = scoreB + 1                       
 else:                             
 serving = "A"          
 return scoreA,scoreB  

# 第三阶段 gameOver()函数:        
def gameOver(a,b):               
return a==15 or b==15 

# printSummary()函数       
def printSummary():            
 n = winsA + winsB            
 print(‘\nGames simulated:%d’%n)           
 print(‘WinsforA:{0}({1:0.1%})’.format(winsA,winsA/n))          
 print(‘Wins for B:{0}({1:0.1%})’.format(winsB,winsB/n)) 

 

 

 

夜光:设计过程总结 


 自顶向下设计: 
 步骤1:将算法表达为一系列小问题; 
 步骤2:为每个小问题设计接口; 
 步骤3:通过将算法表达为接口关联的多个小问题来细化算法; 
 步骤4:为每个小问题重复上述过程。 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值