I am trying to create a simulation but for some reason or other I get an "list index out of range" error. I am not sure what I am doing wrong precisly.
import numpy as np
import math
roomPrice = 280
dayAvailable = [1, 2, 3, 4, 5]
dayDemand = [[1], [2], [3], [4], [5], [1,2], [2,3], [3,4], [4,5], [1,2,3]]
customers = np.random.poisson(lam=250, size=1000)
deny = 0
customersDenied = []
bookings = []
customersHelped = 0
capacityFull = 0
def priceAccept(p):
value = 1/(1 math.exp(0.025*p-7.5))
return value
for c in customers:
capacity = [50, 50, 50, 50, 50]
probability = np.random.choice([0,1,2,3,4,5,6,7,8,9,],
size = c,
p = [0.15,0.05,0.1,
0.05,0.1,0.2,
0.1,0.1,0.05,0.1])
for prob in probability:
for i in dayDemand[prob]:
if capacity[i] == 0:
capacityFull = 1
deny = 1
if capacityFull == 0:
priceAcceptCustomer = np.random.choice([1,0], size = 1, p=[priceAccept(roomPrice),1-priceAccept(roomPrice)])
if priceAcceptCustomer == 1:
for d in dayDemand[prob]:
if capacity[d-1] > 0:
capacity[d-1] -= 1
customersHelped = 1
bookings.append(customersHelped)
customersDenied.append(deny)
It keeps returning the following at if capacity[i] == 0:
IndexError: list index out of range
How can I fix this simulation to run correctly?
CodePudding user response:
Array indexation begin with 0
. So, the maximum value of i
for capacity is 4
. Thus, IndexError: list index out of range
will be raised when i
will be equal to 5
.
CodePudding user response:
Because the size of dayDemand
is 10, capacity
is 5:
print(len(dayDemand)) # 10
print(len(capacity)) # 5
If i > 4 in the loop below, you will get this error because capacity
is not the 6th or capacity[5]
element of the array
for i in dayDemand[prob]:
if capacity[i] == 0:
capacityFull = 1