import hashlib
def calculateab(email):
maxhash = 16**40
emailhash = int(hashlib.sha1(email).hexdigest(), 16)
div = (maxhash/100)-1
return int(float(emailhash/div))
#A small demo
if __name__ == '__main__':
import uuid, time, json
emails = []
verify = {}
for i in range(1000000):
emails.append(str(uuid.uuid4()))
starttime = time.time()
for i in emails:
ab = calculateab(i)
if ab not in verify:
verify[ab] = 1
else:
verify[ab] += 1
#json for your eye's pleasure
print json.dumps(verify, indent = 4)
#if you look at the numbers, you'll see that they are well distributed so
#unless you are going to do that every second for all users, it should work fine
print "total calculation time {0} seconds".format((time.time() - starttime))
你使用的是MySQL,所以很难说是不是个好主意。改变数据库可能代价高昂。而且,如果它开始变大,从长远来看可能会影响性能。此外,您还必须修改您的系统,以便为每个新用户在数据库中包含该号码。您已经将此标记为python问题。所以这里有另一种方法,不用对数据库做任何更改。既然你说的是用户,那么你可能对所有用户都有一个唯一的标识符,比如说电子邮件。我会用uuid代替电子邮件
与python没有多大关系,更多的是一个数学解决方案。你可以使用md5,sha1或者其他任何东西,只要它有固定的长度并且是一个十六进制数。第6行上的
-1
是可选的-它设置的范围是0到99,而不是1到100。您也可以将其修改为使用浮动,这将为您提供更大的灵活性。在对主键运行一个简单的算法。例如,如果用户id有一个整数,用偶数和奇数分开。在
如果您需要两个以上的组,请使用mod函数。在
我将添加一个只有userId和A/B的辅助表,您不需要更改现有的表,如果需要,可以很容易地更改每个类的百分比。它的侵入性很小。在
相关问题 更多 >
编程相关推荐