将字符串列表划分为 n 个分区,这些分区是确定性可重现的(假设 n 可以改变)
我有这个要求,其中我需要随机分配列表中的每个字符串,即 [1,n] 范围内的分区。这些分区应该是可重复的,并且不应该随着 n 的变化而改变。
我可以使用 python 中的 hashlib 轻松实现第一个要求。问题是第二个要求。
例如:
import hashlib
string = "johndoe"
digest = hashlib.md5(string.encode()).hexdigest()
print("Partition id:", int(digest,16)%8)
对于n = 8
,这给了我7。但如果 n = 9
,分区 ID 更改为 4
我如何在不同的 n 上保留和重现给定字符串的分区?
分区数 n 是 [8,50] 中的数字 列表的大小<< 200,000
如果无法复制,是否有一种解决方案可以使卡上分区之间的字符串移动最少?
I have this requirement wherein I need to assign every string in a list, a partition in the range [1,n] randomly. These partitions should be reproducible and should not change on varying n.
I am able to achieve the first requirement pretty easily using hashlib
in python. The issue is the second requirement.
For eg:
import hashlib
string = "johndoe"
digest = hashlib.md5(string.encode()).hexdigest()
print("Partition id:", int(digest,16)%8)
This gives me 7 for n = 8
. But if n = 9
, the partition id changes to 4
How can I retain and reproduce the partitions for a given string on varying n?
The number of partitions n is a number in [8,50]
The size of the list is < 200,000
If reproducing is not possible, is a solution with minimum movement of strings between the partitions on the cards?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论