23 Aug 2012

Pythons collections framework has some nice classes that can be very helpful. I just used the formidable Counter class to check if I got a probability distribution conversion right.

I wanted to generate a random integer in the range of 4 to 8, given an existing value from a uniform distribution between 0 and 1. I came up with a simple way of doing that, but wanted to do a quick test if it actually does what I thought it would do. So I used the Counter class to do a quick test:

>>> from collections import Counter
>>> c = Counter
>>> l = []
>>> for _ in range(1000000):
            random.uniform(0,1)*5 + 3.5)))
>>> c.update(l)
>>> c
Counter({8: 200134, 4: 200130, 5: 199970, 7: 199970, 6: 199796})

Looks like it does the job :)

# lastedited 23 Aug 2012
You are seeing a selection of all entries on this page. See all there are.