Can I repeat random.choice without a loop using a vectorized operation

Viewed 43

I am trying to remove the for loop in the function I defined to calculate probability, can I replicate the same code with some kind of vectorized operation. Below is the piece of code:

import numpy as np 
import statistics as st
import pandas as pd
import itertools as it

def dice_simulation(d,k,nreps):
    cnt = 0
    for rep in range(1,nreps): #defining the number of simulations
        # finding the total for the roll of d dices
        total = sum(np.random.choice(range(1,7),d,replace=True)) 
        print("The total is :",total)
        if total == k:
            cnt = cnt+1 # updating the count if the sum is equal to k
            print("count increased to :",cnt)
    return cnt/nreps #finding the probability

dice_simulation(2,8,100)

What I want to do it repeat

sum(np.random.choice(range(1,7),d,replace=True)

nrep times, so that the sum can be stored in the total variable for each rep, and I can just then compare the total with k.

0 Answers
Related