Riddler race

'''The Kentucky Derby is on Saturday, and a field of 20 horses is slated to run “the fastest two minutes in sports” in pursuit of the right to be draped with a blanket of roses. But let’s consider, instead, the Lucky Derby, where things are a little more bizarre:

The bugle sounds, and 20 horses make their way to the starting gate for the first annual Lucky Derby. These horses, all trained at the mysterious Riddler Stables, are special. Each second, every Riddler-trained horse takes one step. Each step is exactly one meter long. But what these horses exhibit in precision, they lack in sense of direction. Most of the time, their steps are forward (toward the finish line) but the rest of the time they are backward (away from the finish line). As an avid fan of the Lucky Derby, you’ve done exhaustive research on these 20 competitors. You know that Horse One goes forward 52 percent of the time, Horse Two 54 percent of the time, Horse Three 56 percent, and so on, up to the favorite filly, Horse Twenty, who steps forward 90 percent of the time. The horses’ steps are taken independently of one another, and the finish line is 200 meters from the starting gate.

Handicap this race and place your bets! In other words, what are the odds (a percentage is fine) that each horse wins?'''


import random
#Defino una función que le asigna a cada caballo su probabilidad correspondiente
def caballo(pos):
  
  res = random.random()
  
  if res<= (52+2*(pos-1))/100:
    
    return  1
  else:  
    return -1  

#Ahora defino una función que simula una carrera  
def carrera():
  ganadores = [] #Aquí meto los ganadores de la carrera
  
  avance = [0 for i in range(20)] #Aquí registro el avance de cada caballo
  
  cuenta = 0
  # Bucle para actualizar el avance de cada caballo
  while cuenta <1: # Cuando hay un ganador o más, salgo del bucle
    
    for i in range(20):
      
      avance[i] += caballo(i+1)
      
    cuenta += avance.count(200)
    
  for i in range(20):
    
    if avance[i]==200:
      ganadores.append(i+1)
    
  return ganadores
# Ahora una función para simular muchas carreras

def simulacion(num_sim):
  resultados = []
  
  prob = []
  for i in range(num_sim):
    
    resultados += carrera()
    
  for i in range(20):
    cont = 0
    
    for j in resultados:
      
      if j == i+1:
        
        cont +=1
        
    prob.append(100*cont/len(resultados))
    
  return prob
  
print(simulacion(100000))