import math
import matplotlib.pyplot as plt
from random import choice as RC
import seaborn as sns
#Create 9 Lineups, defined by placement of slugger.
#C - 8 contact hitters.
#S - 1 single slugger.
def createLineups() :
lineups = []
for s in range(9):
lineup = ["C"]*s + ["S"] + ["C"]*(8-s)
lineups.append(lineup)
return(lineups)
#Base outcome from hitter.
def calcBase(hitter):
#Pure Contact hitter gets one base one third of time.
if hitter == "C" :
p = RC([0,0,1])
#Slugger hits a homerun one tenth of time.
else :
p = RC([0,0,0,0,0,0,0,0,0,3])
return(p)
#Calculates score of one inning for a lineup.
def calcHomeRuns(lineup):
#Initialize.
outs = 0
base1 = 0
base2 = 0
base3 = 0
score = 0
#Play ball!
while outs < 3 :
#Current hitter.
hitter = lineup[0]
#Update lineup. Places current hitter at end.
lineup = lineup[1:9] + lineup[0:1]
hit = calcBase(hitter)
#No hit = struck out.
if hit == 0:
outs += 1
#Pure Contact.
elif hit == 1:
score += base3
base3 = base2
base2 = base1
base1 = 1
#Slugger
else:
score += base3 + base2 + base1 + 1
base1 = 0
base2 = 0
base3 = 0
return(score)
#Calculate average number of runs achieved by a lineup.
def scoreMonteCarlo(lineup, iterations):
scores = []
for i in range(iterations):
scores.append(calcHomeRuns(lineup))
return(sum(scores) / iterations)
lineups = createLineups()
hrs = []
for l in lineups :
hrs.append(scoreMonteCarlo(l, 100000000))
sns.set()
fig = plt.figure(figsize = (15, 15))
ax = fig.add_subplot()
cmap = plt.cm.get_cmap('viridis_r')
plt.scatter(list(range(1,10)),
hrs,
c = '#29AF7FFF',
s = 2000)
for i in range(9) :
plt.text(i+1,
hrs[i],
round(hrs[i], 4),
ha = 'center',
va = 'center',
c = "#482677FF",
size = 16)
#Title setup.
ax.set_title('Average Number of Home Runs for an Inning', fontsize = 24)
#X-axis setup.
ax.set_xlabel('Slugger Position', fontsize = 22)
#Y-axis setup.
ax.set_ylabel('Home Runs', fontsize = 22)
ax.tick_params(axis = 'both', which = 'major', labelsize = 18)
fig.savefig("2023.08.18 Fiddler.png");