简体   繁体   中英

What is the equivalent of R's function “replicate” in Python?

I am trying to translate some code to do a Monte Carlo Simulation in Python, specifically the following, but am having a hard time finding the equivalent function replicate into my Jupyter Notebook.

estima_probabilidad <- function(clase, num_veces = 10000){
    resultados <- replicate(num_veces, {    # Retorna un vector lógico
        colegas <- sample(dias, clase, replace = TRUE)
        any(duplicated(colegas))
    })

    # Probabilidad:
    mean(resultados) 
}

estima_probabilidad(25)
#> [1] 0.572```

In R, replicate is a wrapper around sapply which itself is just an (optimised) for loop in disguise. So to implement replicate in Python you'd use a for loop.

Example:

In R

replicate(5, 0:2, simplify = FALSE)

In Python

[[*range(3)] for _ in range(5)]
#[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]

Or more abstractly/generally: [your_custom_Python_function_returning_a_list for _ in range(5)] translates to replicate(5, your_vectorised_custom_R_function, simplify = FALSE) .

PS. Your R code is not reproducible; dias seems to be a global variable defined elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM