确保选择之间的最小距离

时间:2014-04-14 16:23:48

标签: python

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import random, collections, time, os

# pseudo-randomly select element from table 
# ensuring minimum distance before the same
# element is selected again

def choice_gen(choices, min_dist):
    last_choices = collections.deque()
    while 1:
        choices = set(choices)
        c = random.choice(list(choices - set(last_choices)))
        new_min = int(len(choices)*6/10)
        if min_dist == new_min:
            last_choices.pop()
        min_dist=new_min
        last_choices.append(c)
        choices = yield c

我编辑了这个发生器,最小距离遵循这个比例:

len(choices):min_dist = 10:6

当new_min int(len(choices)*6/10)的比例结果给出的值发生变化时,deque会因不弹出而增加一个元素的大小。 然后,直到new_min再次变化,它会不断弹出,从而确保双端队列的大小不变。 至少,这应该是它应该做的。我的实施是对的吗?

1 个答案:

答案 0 :(得分:0)

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import random, collections

# pseudo-randomly select element from table 
# ensuring minimum distance before the same
# element is selected again

def choice_gen(choices, min_dist):
    last_choices = collections.deque()
    choices = set(choices)
    while 1:
        c = random.choice(list(choices))
        choices.remove(c)
        last_choices.append(c)
        if len(last_choices) == min_dist:
            choices.add(last_choices.popleft())
        yield c