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

-------------Problems Reply------------

Using the functions from this answer you can generate a list of x random numbers that sum to y.

Iterate over the items of this list and make that many random choices (with removal) from a population of elements for each holder.

Or by example:

# requires RandIntVec() & RandFloats() from linked answer

# whatever population you are choosing from, example letter
population = list('qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890')

# sizes (whatever you want)
num_of_holders = 7
total_elements = len(population)

# empty holder to put results in
element_holder = [[] for _ in xrange(num_of_holders)]

# distribute total_elements elements in randomly-sized portions among num_of_holders 'element holders'
random_portions_in_holder = RandIntVec(num_of_holders, total_elements, Distribution=RandFloats(num_of_holders))

# assign each portion of elements to each 'holder'
for h, portion in enumerate(random_portions_in_holder):
for p in range(portion):
index = random.randrange( len(population) )
element_holder[h].append(population.pop(index))

# display
print 'Randomly-portioned elements'
for h in element_holder:
print h

# verify
print '\nMatch desired result?'
print 'total_elements :', total_elements
print 'elements in holders :', sum([len(h) for h in element_holder])
print 'match :', total_elements == sum([len(h) for h in element_holder])

output

Randomly-portioned elements
['M', 'N', 'f', 'V', 'v', 'h', 'i', 'H', '6', '5', 'j', '7', 'r']
['u', 'Z', 'C', 'I', 's', 'm', 'g', 'p', 'q', 'a', 'O', 'T', 'L']
['K', 'E', 'P', 'U']
['Y', 'D', 'A', 'l', 'J', 'R', 'b', 'c', 'z', 'F']
['0', '1', 'o', 'X', 'G', '4', 'W', '3', '2']
['d', 'Q']
['e', 'y', 'B', '8', 'x', 'k', 'w', 't', 'S', 'n', '9']

Match desired result?
total_elements : 62
elements in holders : 62
match : True

P.S. I had some indentation errors when I copied the linked functions, you may need to correct them. The code under elif Distribution.lower() == 'normal': needs to by un-indented by 1 level. I submitted an edited version (ending approval), so depending on when you copy, you may or may not need to edit.

This isn't actually too difficult. Let's create our containers:

import random

num_containers = 10
num_objects = 100

containers = [[] for _ in range(num_containers)]
objects = (some_object() for _ in range(num_objects))
# we don't need a list of these, just have to iterate over it, so this is a genexp

for object in objects:
random.choice(containers).append(object)

Category:python Views:1 Time:2018-04-15

Related post

  • Break up a square or rectangle into a large number of randomly sized squares or rectangles 2011-10-13

    I'm trying to break up a square or rectangle into a large number of randomly sized squares or rectangles so that none are overlapping. Ok of course others have asked this the best thread I found is How to fill a square with smaller squares/rectangles

  • Split number on random parts 2011-04-16

    How to split one number on several random parts in c#? --------------Solutions------------- Something like this ? static Random rand = new Random(); public IEnumerable<int> Split(int val, int nOfParts) { int remaining = val; for (int i = nOfPar

  • Read a number of random lines from a file in Python 2010-11-05

    Could someone show me how I could read a random number of lines from a file in Python? --------------Solutions------------- Your requirement is a bit vague, so here's another slightly different method (for inspiration if nothing else): from random im

  • How do you split a csv file into evenly sized chunks in Python? 2011-02-10

    In a basic I had the next process. import csv reader = csv.reader(open('huge_file.csv', 'rb')) for line in reader: process_line(line) See this related question. I want to send the process line every 100 rows, to implement batch sharding. The problem

  • Split grid up into random sized rectangles 2011-09-04

    I have a 500 x 400px square with a 100px grid inside it. Now I want to fill that square with smaller random sized square that snap to the grid. This means that the smaller squares can be either 100, 200, 300 or 400 pixels in size. Their size and posi

  • Using random.randint help in python 2012-02-28

    The following code is my attempt at simulating a lottery. import random def lottery(numbers): lottoNumbers = [randint('0,100') for count in range(3)] if numbers == lottoNumbers: print('YOU WIN $10,000') else: print('YOU LOSE,DUN DUN DUNNN!') return n

  • Divide the number into random number of random elements? 2012-04-24

    If I need to divide for example 7 into random number of elements of random size, how would I do this? So that sometimes I would get [3,4], sometimes [2,3,1] and sometimes [2,2,1,1,0,1]? I guess it's quite simple, but I can't seem to get the results.

  • Unable search names which contain three 7s in random order by AWK/Python/Bash 2009-03-12

    I need to find names which contain three number 7 in the random order. My attempt We need to find first names which do not contain seven ls | grep [^7] Then, we could remove these matches from the whole space ls [remove] ls | grep [^7] The problem in

  • Splitting out the output of ps using Python 2009-03-25

    On Linux, the command ps aux outputs a list of processes with multiple columns for each stat. e.g. USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND ... postfix 22611 0.0 0.2 54136 2544 ? S 15:26 0:00 pickup -l -t fifo -u apache 22920 0.0 1.5 19

  • Select variable number of random records from MySQL 2009-02-17

    I want to show a random record from the database. I would like to be able to show X number of random records if I choose. Therefore I need to select the top X records from a randomly selected list of IDs (There will never be more than 500 records inv

  • How do I pick 2 random items from a Python set? 2009-08-11

    I currently have a Python set of n size where n >= 0. Is there a quick 1 or 2 lines Python solution to do it? For example, the set will look like: fruits = set(['apple', 'orange', 'watermelon', 'grape']) The goal is to pick 2 random items from the

  • IMEI number of a mobile phone using python 2010-02-22

    How can I get the IMEI number of a mobile phone using Python? Thanks in advance. Nimmy --------------Solutions------------- Sending AT+CGSN through the appropriate serial device will have it return the IMEI.

  • CSS Layout full of random sized divs 2010-08-01

    Possible Duplicate: Any ideas on how I could implement a grid-view in CSS? - CSS I'm trying to create a layout that is backward from what I usually do. I have hundreds of randomly sized divs that I want to fill in as much of the page as possible. As

  • Fetch Specific Number of Random Rows from CoreData 2010-09-20

    I'm using the code below to Fetch a queried set of all rows using CoreData matching the search criteria: itemType = 1. But what I need to do is to Fetch a specific number of Random rows from the data instead. For example, instead of retrieving all 10

  • Get Line Number of certain phrase in file Python 2010-10-18

    I need to get the line number of a phrase in a text file. The phrase could be: the dog barked I need to open the file, search it for that phrase and print the line number. I'm using Python 2.6 on Windows XP This Is What I Have: o = open("C:/file.txt"

  • Positioning multiple, random sized, absolutely positioned elements so they don't overlap 2011-06-03

    Ok I need to be able to position a bunch of random sized absolutely positioned words on a page but I don't want any of the elements to overlap. The end goal is to have a fluid word cloud that responds to user interaction (remember the Google Balls Do

  • CSS: Create a tessellating wall of random sized rectangles 2011-10-26

    I want to create a wall of quotes that are contained inside different colored rectangles. Obviously, the quotes will be different lengths and I want the rectangles to be randomly sized widths - which will mean the heights are going to be correspondin

  • Get arbitrary number of random elements from a php array in one line 2012-01-19

    I wanted to pull an arbitrary number of random elements from an array in php. I see that the array_rand() function pulls an arbitrary number of random keys from an array. All the examples I found online showed then using a key reference to get the ac

  • How to generate a list which contains a given number of random numbers within a range in Haskell? 2012-02-04

    I know how to generate a single random number within a given range, a list of random numbers, a list which contains a given number of random numbers but NOT a list which contains a given number of random numbers within a RANGE. Can anyone help me on

  • Why is splitting a string slower in C++ than Python? 2012-02-21

    I'm trying to convert some code from Python to C++ in an effort to gain a little bit of speed and sharpen my rusty C++ skills. Yesterday I was shocked when a naive implementation of reading lines from stdin was much faster in Python than C++ (see thi

  • PHP format split number into separate html tags 2012-02-29

    How would I go and split number 12345 into something like this with PHP: <span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> --------------Solutions------------- echo

  • How to Avoid Repeated Number in Random Generation WP7? 2012-04-24

    I want random number in one array. array like this int[] random={"1","2","3","4","5"}; I want to take these number randomly. its working fine but value are repeating. i don't wont repeated value. i want random number without repeating same number. I

  • My laptop screen is split horizontally and the lower portion appears grayish. 2013-05-06

    original title: Splitted screen My laptop screen is split horizontally and the lower portion appears grayish. When I re-start the laptop the screen sometimes appears OK but sometimes split again. What do I do to stop the splitting? --------------Solu

  • Split value in 24 randomly sized parts using C# 2009-10-17

    I have a value, say 20010. I want to randomly divide this value over 24 hours. So basically split the value into a 24 slot big array where all slots are randomly big. What could be a good way solving this using C#? --------------Solutions------------

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.079 (s). 11 q(s)