<jupyter_start><jupyter_text>DSE210 Worksheet 4 Question 6https://drive.google.com/file/d/0BxK4UNZY50IFNVRRRG5iVnNMbE5MVWpnZ2t6NDBlYXd2M3dj/view> There is a dormitory with n beds for n students. One night the power goes out, and because it is dark, each student gets into a bed chosen uniformly at random. What is the expected number of students who end up in their own bed?I had trouble believing the analytical solution that only 1 student would be expected to find their original bed. So-- armed with the power of Python-- I figured I would code it and see if a Monte Carlo would come up with the same answer.<jupyter_code>import numpy as np
from matplotlib import pyplot as plt
from numpy.random import permutation
NUM_BEDS = 20   # Number of people/Number of beds
NUM_TRIALS = 10000  # Number of times to rerun the experiment
originalBeds = range(1,NUM_BEDS)
beds = np.matrix(permutation(originalBeds))
for i in range(NUM_TRIALS):
    newBeds = permutation(originalBeds)
    beds = np.append(beds, np.matrix(newBeds), axis=0)
beds
foundOwnBed = ((beds - originalBeds) == 0) 
numFound = np.ravel((np.squeeze(foundOwnBed.sum(axis=1)))) # Sum per trial of how many students found their original bed
plt.hist(numFound)
plt.title('Histogram')
plt.xlabel('Number of students who found their own bed')
plt.ylabel('Number of trials')
plt.show()
numFound
averageFoundBed = np.mean(numFound)
print("On average {} person(s) found their original bed.".format(averageFoundBed))<jupyter_output>On average 0.9891010898910109 person(s) found their original bed.
{'fraction_non_alphanumeric': 0.08, 'fraction_numerical': 0.02838709677419355, 'mean_word_length': 5.254032258064516, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 5, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '265413', 'license': 'Unlicense', 'n_tokens_mistral': 530, 'n_tokens_neox': 484, 'n_words': 186, 'path': 'Bed hopping.ipynb', 'repo_name': 'mas-dse-greina/dse210', 'size': '1550'}