dimanche 23 décembre 2018

Dynamic increase of if-else statements

I have "n" if-else conditions, but "n" is not fixed, it is dynamic. Is there a way to write a dynamic amount of if-else conditions?

Below is the code for "n=6".

import numpy as np

n=6 #number of persons 
N=10000 # Number of simulations

pers = np.zeros((n,1))

for i in range(N):
  a = np.random.randint(0,n,1)

  if a==0:
    pers[0]+=1
 else:
    a= np.random.randint(0,n-1,1)
    if a==0:
        pers[1]+=1
    else:
        a= np.random.randint(0,n-2,1)
        if a==0:
            pers[2]+=1
        else:
            a= np.random.randint(0,n-3,1)
            if a==0:
                pers[3]+=1
            else:
                a= np.random.randint(0,n-4,1)
                if a==0:
                    pers[4]+=1
                else:
                    pers[5]+=1

Aucun commentaire:

Enregistrer un commentaire