samedi 2 mai 2015

Split number in randomly-sized portions in Python

I have x = 10 and y = 100.

Can I distribute y elements in randomly-sized portions among x 'element holders'?

I want to create x categories each with a random number of items; however, the number of items created should be exactly y.

I guess it's something like

# number of categories and items
x = 10, y = 100

# keep track of how many items we have left to add
y_left = y

# create all categories
for i in range(x):
    # create category

    # find number of items in this category
    num_items_in_category = random.randint(1, y_left)

    # create items
    for j in range(num_items_in_category):
        # create item

    # set new number of items left to add
    y_left -= num_items_in_category




Aucun commentaire:

Enregistrer un commentaire