Skip to content

Instantly share code, notes, and snippets.

@quake0day
Created March 20, 2016 21:52
Show Gist options
  • Save quake0day/f0553cbdbac07b3d2b68 to your computer and use it in GitHub Desktop.
Save quake0day/f0553cbdbac07b3d2b68 to your computer and use it in GitHub Desktop.
Consistent Hashing II - Python_TLE
import random
class Solution:
# @param {int} n a positive integer
# @param {int} k a positive integer
# @return {Solution} a Solution object
@classmethod
def create(cls, n, k):
# Write your code here
t = cls(n, k)
return t
def __init__(self, n, k):
self.n = n
self.k = k
self.valuelist = [i for i in xrange(self.n)]
self.h = {}
# @param {int} machine_id an integer
# @return {int[]} a list of shard ids
def addMachine(self, machine_id):
# write your code here
res = random.sample(self.valuelist, self.k)
for e in res:
self.h[e] = machine_id
self.valuelist.remove(e)
return res
# @param {int} hashcode an integer
# @return {int} a machine id
def getMachineIdByHashCode(self, hashcode):
# write your code here
while hashcode not in self.h:
hashcode += 1
return self.h[hashcode]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment