将字符串列表划分为 n 个分区,这些分区是确定性可重现的(假设 n 可以改变)

发布于 2025-01-16 05:04:13 字数 516 浏览 2 评论 0原文

我有这个要求,其中我需要随机分配列表中的每个字符串,即 [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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文