# how to choose element from list based on probabilities?

Sidharthk sidharthk at hotmail.com
Sun Nov 16 12:24:00 CET 2003

```sidharthk at hotmail.com (Sidharthk) wrote in message news:<8d02ff63.0311150944.3e709a49 at posting.google.com>...
> import random
> import math
> def getCircleMaker(circleList):
>     circleList = list(circleList)
>     circleList.sort(lambda a, b: cmp(b.r, a,r))
>     def workerFunc():
>         pos = int(random.randrange(len(circleList)**2)**0.5)
>         return circleList.pop(pos)
>     return workerFunc
>
>
>
My earlier example wont work. It orders the list incorrectly so you
are more likely to end up with a smaller circle.
here's a corrected example.
class Circle:
def __init__(self, x,y,r):
self.center =(x,y)
self.r = r

import random
def getCircleMaker(circleList):
circleList = list(circleList)
circleList.sort(lambda a, b: cmp(a.r, b.r))
pow = 4
def workerFunc():
pos = int(random.randrange(len(circleList)**pow)**(1.0/pow))
return circleList.pop(pos)
return workerFunc

circlelist = [Circle(0,0,random.randrange(100)) for e in range(100)]

getCircle =  getCircleMaker(circlelist)

Changing the value of pow will affect the probability of getting a
larger circle. The larger the value of pow the higher the chance.

```