how to choose element from list based on probabilities?
Sidharthk
sidharthk at hotmail.com
Sat Nov 15 12:44:21 EST 2003
Matthew Wilson <mwilson at sarcastic-horse.com> wrote in message news:<slrnbr81e4.gp0.mwilson at overlook.homelinux.net>...
> I have a list of very simple circle objects:
>
> class Circle:
> def __init__(self, x,y,r):
> self.center =(x,y)
> self.r = r
>
> I want to write a function that accepts a list of circle objects and
> then chooses one of the circles and returns that circle. The circles
> with the biggest areas should be the most likely to be chosen, but there
> should be some randomness.
>
> Subsequent calls to the function should not return the same circle.
>
> Can anyone help me out?
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
circlelist = [Circle(0,0,random.randrange(100)) for e in range(100)]
getCircle = getCircleMaker(circlelist)
and now just call getCircle() to get a circle
This is a very simple solution. getCircle will raise an IndexError
when the list finishes.
I havent really tried this but it should work in principle. :-)
More information about the Python-list
mailing list