Last active
May 15, 2017 18:17
-
-
Save finiteautomata/bef2b2829b631e59ff5f7a3fa9736977 to your computer and use it in GitHub Desktop.
Function that returns a list of m integers that sums n
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
def random_balls_in_bins(balls, bins): | |
""" | |
Returns a list of <bins> integers that sum <balls> | |
We can think this as a problem of bosons: | |
We have to distribute balls in bins. To model this, we use a shuffle of | |
'o' * balls + '|' * (bins-1) | |
This results in a string of the form oo|ooo|oo where we leave the last '|' fixed | |
Parameters: | |
---------- | |
balls: int > 0 | |
number of balls to distribute | |
bins: int > 0 | |
number of bins | |
Returns | |
------- | |
A list of <bins> integers that sum <balls> | |
""" | |
balls_and_bins = list('o' * balls + '|' * (bins-1)) | |
random.shuffle(balls_and_bins) | |
bins = [] | |
current = 0 | |
for e in balls_and_bins: | |
if e == 'o': | |
current +=1 | |
elif e == '|': | |
bins.append(current) | |
current = 0 | |
bins.append(current) | |
return bins |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment