im new to python and im trying to solve this problem for school.
Airlines find that each passenger who reserves a seat fails to turn up with probability q independently of the other passengers. So Airline A always sell n tickets for their n−1 seat aeroplane while Airline B always sell 2n tickets for their n − 2 seat aeroplane. Which is more often over-booked?
This is my code:
import random
arrive = [True, False]
def airline_a(q, n, sims):
sim_counter = 0
reserved_seats = []
overbooked = 0
for x in range(n):
reserved_seats.append(x)
while sim_counter != sims:
passengers = 0
for x in range(len(reserved_seats)):
success = random.choices(arrive, weights=(100 - (q * 100), q * 100), k=1)
if success == True:
passengers += 1
if passengers > n - 1:
overbooked += 1
sim_counter += 1
print("Results: ")
print(f"Probability that Airline A is overbooked: ", overbooked / sims)
airline_a(.7, 100, 1000)
I am supposed to do a similar function for airline B and compare both values, however i came across an issue The problem is that the output is always 0. I dont quite understand what I'm doing wrong.
The problem with your code is this line: if success == True:
. If you try printing success
, it outputs either [True]
or [False]
. You can fix this by taking the first value of success
in the if
statement like this:
if success[0] == True:
passengers += 1
and to simplify the code a bit:
if success[0]:
passengers += 1
Change your code to the following to fix the error, however the count for the variable passengers
will remain below the variable n
, still resulting 0, so try and reduce the value of n or by reducing the value of q
:
import random
arrive = [True, False]
def airline_a(q, n, sims):
sim_counter = 0
reserved_seats = []
overbooked = 0
for x in range(n):
reserved_seats.append(x)
while sim_counter != sims:
passengers = 0
for x in range(len(reserved_seats)):
success = random.choices(arrive, weights=(100 - (q * 100), q * 100), k=1)
if success[0]:
passengers += 1
if passengers > n - 1:
overbooked += 1
sim_counter += 1
print("Results: ")
print(f"Probability that Airline A is overbooked: ", overbooked / sims)
airline_a(.7, 100, 1000)
For an explanation on random.choices()
visit the following link