Help a retarded new programmer out.
<pic>
here's a really dumb way
t[random(0,2)]
>>61177663
Forgot to mention this is a problem from Think Python, i.e python programming language.
>>61177735
hist[key] / sum(hist.values())
>>61177766
btw I don't understand the answer given in >>61177663 at all
>>61177766
My first attempt was using random.random() to generate a number and check if it was <= the probability of hist[key] / sum(hist.values()) with a for loop.
>>61177766
Oh shit sorry I mostly just read the last sentence - that's just going to return the probability of they key you specifically provide.
>>61177608
Naive solutionimport random
hist = {'a':2, 'b':1}
a = []
for k,v in hist.items():
for i in range(v):
a.append(k)
print(random.choice(a))
>>61177608
take a random number between 0 and the sum of the histogram entries.
Then just count through each entry, If you rolled a 3 for instance, in the example of above, you'd start at a and count for as many times as a has entries, then you'd go to the next letter, b. You count once for b's one entry and then you stop because your count equals the number you rolled. Then just return whatever number you're on.
Maybe there's a better way that's faster or something but this way is piss easy.
from random import choice
choice(sum([[k] * v for k, v in hist.items()], []))
>>61177946
>kill you are self.
Convert the histogram dict into a list like in your pic.import random
def choose_from_hist(hist):
t = []
for k, v in hist.iteritems():
t.extend([k] * v)
return random.choice(t)
>>61178008
This was my initial solution as well but I didn't think OP would get the code...
>>61178038
This is great as well
>>61178038
OP this is basically the clear version of what I code golf'd here >>61178008
>>61177893
Glorious, thank you.
>>61177946
Not nice, wtf.
>import random
>>61178008
That's a great solution I haven't worked much on list comprehensions yet so it was difficult to understand at first.
I don't... understand why this is a question. random.choice literally already does this. 5 minutes of RTFM would have solved this for you: https://docs.python.org/2/library/random.html
ITT: idiots who can't comprehend memory complexityimport random
def choose(hist={}):
choice = None
choices = (
k for k, v in hist.items()
for _ in range(v)
)
choice_idx = random.randint(0, sum(hist.values()))
for _ in range(choice_idx):
last = next(choices)
return last
>>61178687
Holy shit, this is some /r/programminghorror material. I really hope you're trolling.
>>61177608
http://www.keithschwarz.com/darts-dice-coins/
>>61178015
worst 2hu
>>61178687
>Average pythonist