INTRODUCTION

A group of 20 students are giving Christmas gifts to each other. Everyone writes their own name on a piece of paper and puts it into the box. Then take away one name from the box at random and check who will be gifted. 

What is the probability that at least one student will draw himself?

To solve the problem you can use derangement or subfactorial. It’s a number of permutations that no element appears in its original position.

For 20 people, the probability that no one will pick themselves is:

$P(A) = \frac{!20}{20!} \approx 36\%$

So the probability that at least one person picks themselves is:

$P(A’) = 1-\frac{!20}{20!} \approx 64\%$

Check the example of subfactorial of number 4: Podsilnia

More:


PYTHON CODE

import random

n = 20
num_trials = 100
count = 0
for i in range(num_trials):
    students = list(range(1, n + 1))
    random.shuffle(students)
    for j in range(n):
        if students[j] == j + 1:
            print(f'Trial {i+1}, student {j+1} drew themselves')
            count += 1
            break
print(f'\nIn {count} out of {num_trials} trials, someone drew themselves.')

⬆️⬆️⬆️ See in Google Colaboratory


HOW THE CODE WORKS?

  1. We start by importing the random library
  2. We set the number of students per class to 20
  3. We set the number of simulation attempts to 100
  4. In the for loop (for each trial), the program creates a list of students using a function range i list() and shuffles it using a function shuffle().
  5. In the second for loop (for each student), the program checks whether the number drawn for the student corresponds to its own number, and then prints information that this situation has occurred.
  6. If a match is found, the program increments the value of the variable count (number of hits) and breaks the loop so that no more students are checked. We are no longer interested in whether another student also draws himself and speeds up the operation of the entire program.
  7. At the end, the program prints information about the number of hits in relation to the number of attempts.
  8. At the end, the program prints information about the number of hits in relation to the number of attempts.