lundi 12 octobre 2020

Create iterable of numbers with specified occurrences and random ordering

I am searching for an efficient way to create an iterable that yields integers with specified occurrences in random ordering.

My current approach is to create a list from a number-occurrence mapping and shuffle it:

import random

def get_random_iterable(occurrences):
    rand_list = []

    for number, occurrence in occurrences.items():
        for i in range(occurrence):
            rand_list.append(number)
    
    random.shuffle(rand_list)
    return rand_list

occurrs = {    # specify occurrences:    number: occurrence
    0: 2,
    1: 1,
    2: 3,
    3: 0,
}

print(get_random_iterable(occurrs))         # output:    [1, 2, 2, 0, 0, 2]

Which other reasonable approaches exist? I appreciate any alternative solutions or improvements.




Aucun commentaire:

Enregistrer un commentaire