Skip to content

Instantly share code, notes, and snippets.

@antonio-catalano
Created April 8, 2018 00:39
Show Gist options
  • Save antonio-catalano/5b3fc8d8617415221d3f63856e908b9f to your computer and use it in GitHub Desktop.
Save antonio-catalano/5b3fc8d8617415221d3f63856e908b9f to your computer and use it in GitHub Desktop.
''' A tennis club invites 32 players of equal ability to compete in an elimination tournament.
(Only the winner of the pair will stay for the next round)
What is the probability that a particular pair of players will meet during the tournament?'''
import random
count = 0
def recursive_round(a): # we create a recursive function to simulate the tournament where the argument is a list
if len(a) == 1:
return a[0]
else:
lista = []
print()
for i in range (1,int(len(a)/2 + 1)):
x = random.choice(a)
a.remove(x)
y = random.choice(a)
a.remove(y)
match = ("The {} match is: {} vs {}".format(i,x,y))
print(match)
if (x,y) == (1,2) or (x,y) == (2,1): #every time that the couple (1,2) happens, we update the count.
global count
count += 1
winner1 = random.choice((x,y))
lista.append(winner1)
return(recursive_round(lista))
N = 1000000 # montecarlo method
for i in range(N): # we generate the tournament 1 million of times (it takes a lot of time)
recursive_round([i for i in range (1,33)]) # [i for i in range (1,33)] is the list of 32 players and this is the
# argument of our function
print()
print("The couple (1,2) happened {} times".format(count))
print()
print("Probability is: ", float(count / N)) # the result is around 1/16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment