开发者

Summing the number of instances a string is generated in iteration

Working in python 2.7.

I'm trying to work my way up to plotting a random walk. But first I'm having some trouble summing the number of results I get from a random generator.

The fir开发者_Go百科st piece of code:

def random_pick(some_list, probabilities):
x = random.uniform(0,1)
cumulative_probability = 0.0
for item, item_probability in zip(some_list, probabilities):
    cumulative_probability += item_probability
    if x < cumulative_probability: break
return item

In this case, the list is a = ['Hit', 'Out'] and the respective probabilities are given by b = [.3, .7]. This code returns 'Hit' with probability .3 and 'Out' with probability .7.

I then have code to create a rough sim of a player's batting average based on those probabilities:

def battingAverage(atBats, i, some_list=a, probabilities=b):
for i in range(1,atBats):
    if random_pick(a, b) == 'Hit':
        hit = random_pick(a, b)
        print '%.0f: %s' % (1, 'Hit')
    elif random_pick(a, b) == 'Out':
        out = random_pick(a, b)
        print '%.0f: %s' % (2, 'Out')

When I run this, I get a random generation of as many at-bats as a I choose. But I would like to be able to then sum the number of instances or both hit and out, but I have not been able to figure out how. I've tried to use code similar to below after changing the random_pick to return the probability instead of the item, but to no avail.

def battingAverage(atBats, i, some_list=a, probabilities=b):
num_hits = 0
num_outs = 0
for i in range(1,atBats):
    if random_pick(a, b) == 'Hit':
        hit = (random_pick(a, b))/.3
        num_hits += hit
    elif random_pick(a, b) == 'Out':
        out = (random_pick(a, b))/7
        num_outs += out
print num_hits, num_outs

Any help would be greatly appreciated. Also, does anyone know of a good resource to learn Monte Carlo simulations?


num_hits = 0
num_outs = 0
for i in range(1, atBats):
    if random_pick(a,b) == 'Hit':
        num_hits += 1
    else:
        num_outs += 1
print num_hits, num_outs


To be honest, I am struggling to follow the logic of your code (it's been a long day), but here are a couple of pointers:

1) When you do things like:

if random_pick(a, b) == 'Hit':
   ...
elif random_pick(a, b) == 'Out':
   ...

you're calling random_pick() twice, so you're conducting two independent simulations instead of one. As a result, it could be that neither of the two branches get executed. To fix, call random_pick() once, store the result, and then branch on that result.

2) As to your other problem, Python allows you to return multiple values from a function. This might be useful here:

def random_pick(some_list, probabilities):
   ... decide on the item and probability ...
   return item, probability

You can then call it like so:

item, prob = random_pick(a, b)

and use item or prob (or both).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜