Help a retarded new programmer out.
Help a retarded new programmer out
Other urls found in this thread:
docs.python.org
keithschwarz.com
twitter.com
here's a really dumb way
t[random(0,2)]
Forgot to mention this is a problem from Think Python, i.e python programming language.
hist[key] / sum(hist.values())
btw I don't understand the answer given in at all
My first attempt was using random.random() to generate a number and check if it was
Oh shit sorry I mostly just read the last sentence - that's just going to return the probability of they key you specifically provide.
Naive solution
import 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))
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()], []))
>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)
This was my initial solution as well but I didn't think OP would get the code...
This is great as well
OP this is basically the clear version of what I code golf'd here
Glorious, thank you.
Not nice, wtf.
>import random
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: docs.python.org
ITT: idiots who can't comprehend memory complexity
import 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
Holy shit, this is some /r/programminghorror material. I really hope you're trolling.
worst 2hu
>Average pythonist