0

I have a study related "problem". I'm trying to write as functional/side-effect free code as possible in Python. The problem ist as follows:

I need to choose x items from a list based on different probabilities for each item. The newly chosen items may not be chosen yet, so no "putting back".

How could I achieve this without traditional loops or reassignments/changes to variables?

  • 1
    Does [this](https://stackoverflow.com/questions/3679694/a-weighted-version-of-random-choice) answer your question? You can use `random.choice` and provide the weights/probabilities of each item in your sequence. – Cory Kramer Apr 29 '21 at 19:52
  • Yes, it does! Thanks a lot! However, I'd like to understand how I could achieve this by myself, for learning purposes! – Omniscient Potato Apr 29 '21 at 20:02
  • Well, in a functional programming sense, you could say: drawing n items without replacement is the same as drawing one item and then n - 1 more items on a reduced problem (excluding the chosen item and scaling up the weights so the remaining ones sum to 1). I think it would be easy to get it working; an efficient implementation might be more of a challenge. Good luck and have fun. – Robert Dodier Apr 30 '21 at 00:13

0 Answers0