Skip to content

Instantly share code, notes, and snippets.

@snyh
Created December 12, 2012 14:02
Show Gist options
  • Save snyh/4267925 to your computer and use it in GitHub Desktop.
Save snyh/4267925 to your computer and use it in GitHub Desktop.
generate random element from an list with gurantee at least "n" element is not same. (n is default the length of the list)
import random
class DistanceRandom:
def __init__(self, v_range, v_distance=None):
if v_distance == None:
v_distance = len(v_range)
assert(len(v_range) >= v_distance >= 1)
self.freshed = v_range
self.dist = v_distance
self.used = []
def get(self):
if len(self.used) >= self.dist:
t = self.used.pop()
self.freshed.append(t)
v = self.freshed.pop(random.randint(0, len(self.freshed) - 1))
self.used.insert(0, v)
return v
r = DistanceRandom(range(12))
for i in range(200):
print r.get()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment