我会用dict在玩家之间“切换”:
other = {'A':'B', 'B':'A'}
然后,如果服务等于’A’,那么其他[服务]将等于’B’,如果服务等于’B’,则其他[服务]将等于’A’.
In [1]: import collections
In [2]: score = collections.Counter()
In [3]: score['A'] += 1
In [4]: score['A'] += 1
In [5]: score['B'] += 1
In [6]: score
Out[6]: Counter({'A': 2, 'B': 1})
还要注意这段代码中的内容
if serving == "A":
for i in range(2):
if random() < probA:
scoreA += 1
else:
scoreB += 1
else:
for i in range(2):
if random() < probB:
scoreB +=1
else:
scoreA += 1
有两个块基本上是相同的想法重复两次.这表明可以通过使用函数来加强代码.例如,我们可以定义一个函数服务,当给出概率概率时,玩家(A或B)返回获胜的玩家:
def serve(prob, player):
if random.random() < prob:
return player
else:
return other[player]
然后上面的代码就会变成
for i in range(2):
winner = serve(prob[serving], serving)
score[winner] += 1
因此,您可以通过以下方式使代码紧凑:
import random
import collections
other = {'A':'B', 'B':'A'}
def serve(prob, player):
if random.random() < prob:
return player
else:
return other[player]
def simOneSet(probA, probB):
prob = {'A':probA, 'B':probB}
score = collections.Counter()
serving = "A"
while not setOver(score['A'], score['B']):
for i in range(2):
winner = serve(prob[serving], serving)
score[winner] += 1
if score['A'] == 10 and score['B'] == 10:
winner = serve(prob[serving], serving)
score[winner] += 1
serving = winner
return score['A'], score['B']
def setOver(scoreA, scoreB):
return max(scoreA, scoreB) >= 21
print(simOneSet(0.5,0.5))