Replacing Sublists with Different Probabilities in GHPython

I’m currently working on a GHPython script where I’ve successfully divided a list into sublists, each containing four elements. Now, I’m facing the challenge of replacing some of these sublists with other lists randomly, using different probabilities. For instance, I aim to replace the sublist `[1, 0, 1, 1]` with `[1, 1, 1, 1]` with a probability of 60%, `[1, 2, 1, 1]` with a probability of 20%, and `[1, 3, 1, 1]` with a probability of 20%.

Since GHPython doesn’t offer the `random.choices()` function and `random.choice()` doesn’t support specifying weights for selection, I’m seeking guidance on implementing this functionality without relying on external libraries like NumPy. Additionally, once I’ve successfully replaced these sublists, how can I structure the output as a data tree within Grasshopper, or at least ensure that the output doesn’t appear as a list of `IronPython.Runtime.List` objects?@Mahdiyar

You can make your own ‘choices’ function like this:

``````import random

def choices(population, weights, k=1):
total_weight = float(sum(weights))
cum_weights = [sum(weights[:i+1]) / total_weight for i in range(len(weights))]

samples = []
for _ in range(k):
rand = random.random()
for i, cum_weight in enumerate(cum_weights):
if rand < cum_weight:
samples.append(population[i])
break

return samples

# Example
a = choices(['A', 'B', 'C', 'D'], [0.1, 0.3, 0.2, 0.4], 10000)
``````

Mahsa.gh (10.9 KB)

``````import ghpythonlib.treehelpers as th
my_list = [[1, 2, 3], [3, 4]]
a = th.list_to_tree(my_list)
``````
2 Likes

Thanks a lot!