Created
December 12, 2012 14:02
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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