<jupyter_start><jupyter_text>Lab Exercise 9 Solutions (Total Marks: 20)Deadline for submission: Two weeks from your lab session (eg, Tuesday/Friday $\rightarrow$ 11:59 pm of Tuesday/Friday two weeks later)    Rename your file as AXXXXXXXY_LabEx9.ipynb, where AXXXXXXXY is your matric number. **Question 1**Write a program that uses the Monte Carlo method to estimate the area of a triangle with coordinates (0,0), (p,0) and (p,q) within a unit square. Your program is to perform the following:- Prompt user for the number of points and $p,q (0<p<1.0; 0<q<1.0)$- Output the areas from theory and simulation- Display an appropriate plot to show the simulation(Hint: Consider the equation of the line joining (0,0) and (p,q) when determining whether points lie within or outside the triangle. You may refer to Example 5 or 6 for a guide.) **Question 2**Write a program to simulate a simplified version of a casino game known as Jackpot. On each attempt, a set of three letters will be selected from a collection of "A", "B", "C", "D" or "E" randomly with equal probability. Each attempt costs **1** dollar. If the three letters selected are consecutively "A" or "B" (i.e. "AAA" or "BBB"), the player wins **50** dollars. Your program is to perform the following:- Prompt user for the number of attempts N- Plot a histogram of the net amount won/lost for all N attempts- Compute the expected winning or loss per attempt (i.e. (net amount won)/N or (net amount lost)/N respectively)(Hint: You may proceed by writing a loop over N attempts, with each attempt containing a 3-letter sequence that is independent of previous attempts. Compare the letters and update the net amount accordingly after each comparison. Consider the use of a list to hold the three letters that should be reset before the next attempt. Also append the updated net amount for each attempt to another list before the next attempt.)**Food for thought**: For a very determined player who attempts a very large number of times, will the expected net amount more likely to result in a winning or a loss?  Question 1 (10 marks)<jupyter_code>%reset
import numpy as np
import matplotlib.pyplot as plt

nPoints = eval(input("Enter the number of points to be used in the simulation: ")) 
# Ideal to use more points, but not way too many. 100,000 points is ideal for a close estimation.

# Prompt for triangle's base
p = eval(input("Enter the base of the triangle in the simulation: "))

# Prompt for triangle's height
q = eval(input("Enter the height of the triangle in the simulation: "))

# Initialisation
nArea = 0 
ix = []; iy = []
ox = []; oy = []

# Simulation 
for n in range(nPoints):
    x = np.random.rand()
    y = np.random.rand()
    if (x <= p) and (y <= q) and (y/x <= q/p):   # Point lies within the triangle
                                                 # y/x is the hypotenuse, or is the gradient m in the equation y = mx
        nArea += 1
        ix.append(x)
        iy.append(y)
    else:                                        # Point lies outside the triangle
        ox.append(x)
        oy.append(y)
        
# Compare areas from Monte Carlo simulation with actual area
print("Area of the triangle from theory =", 0.5*p*q)
print("Area of the triangle from simulation =", nArea/nPoints)

plt.figure(1,(7,7)) 
plt.plot(ix,iy,"ro") 
plt.plot(ox,oy,"bo") 
plt.plot([0,p,p],[0,q,0],"k--")
plt.xlim(0,1); plt.ylim(0,1)
plt.title("Plot of Simulated Points within a Unit Square and Triangle")
plt.xlabel('x')
plt.ylabel('y')       
plt.show()<jupyter_output>Once deleted, variables cannot be recovered. Proceed (y/[n])? y
Enter the number of points to be used in the simulation: 10000
Enter the base of the triangle in the simulation: 0.4
Enter the height of the triangle in the simulation: 0.7
Area of the triangle from theory = 0.13999999999999999
Area of the triangle from simulation = 0.1407<jupyter_text>Question 2 (10 marks)<jupyter_code>%reset
import matplotlib.pyplot as plt
import numpy as np

import numpy.random as r

r.seed(121) 

N = eval(input("Enter the number of attempts in the Jackpot: "))
outcome = []     # List to store the outcome values
amount = []      # List to store the net amount won or lost after each attempt
netamount = 0    # Initialise the net amount

for n in range (N):
    for i in range(3):            # range(3) is used since there are only 3 letters 
        p = np.random.rand()      # Generate a random number in [0,1)
        if 0 <= p < 0.2:          # Set range of values for "A" to be selected
            outcome.append("A")
        elif 0.2 <= p < 0.4:      # Set range of values for "B" to be selected
            outcome.append("B")
        elif 0.4 <= p < 0.6:      # Set range of values for "C" to be selected
            outcome.append("C")
        elif 0.6 <= p < 0.8:      # Set range of values for "D" to be selected
            outcome.append("D")
        else:                     # For a random number in [0.8, 1), "E" will be selected
            outcome.append("E")
    if outcome[0] == "A" and outcome[1] == "A" and outcome[2] == "A":
        netamount += 49
    elif outcome[0] == "B" and outcome[1] == "B" and outcome[2] == "B":
        netamount += 49
    else:
        netamount -= 1
    outcome = []   # Reset the list
    amount.append(netamount)   # Save each net amount

print(amount)   # Output the net amount for each of the N attempts

bins = 20
plt.figure(1,(7,5)) 
plt.hist(amount,bins)
plt.title("Histogram of winning/loss after " + str(N) + " attempts")
plt.xlabel("Net Gain/Loss");plt.ylabel("Frequency")
plt.show()

win_loss = netamount/N
if win_loss > 0:
    print("Expected winning per attempt = ",win_loss)
elif win_loss < 0:
    print("Expected loss per attempt = ",win_loss)
else:
    print("You have not won or lost.")<jupyter_output>Once deleted, variables cannot be recovered. Proceed (y/[n])? y
Enter the number of attempts in the Jackpot: 100000
[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, -67, -18, -19, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, -60, -61, -62, -63, -64, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, -67, -68, -69, -70, -71, -72, -73, -74, -75, -76, -77, -78, -7[...]
{'fraction_non_alphanumeric': 0.13993826253123623, 'fraction_numerical': 0.07114508305159488, 'mean_word_length': 2.8181818181818183, 'pattern_counts': {'":': 2, '<': 23, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 3, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '205097', 'license': 'MIT', 'n_tokens_mistral': 2535, 'n_tokens_neox': 2250, 'n_words': 985, 'path': 'analysis/LabEx9_Solutions.ipynb', 'repo_name': 'clarence-ong/COS2000-Solutions', 'size': '6803'}