如何从python and.getState()中得出便携式种子?

发布于 2025-01-27 07:57:05 字数 1316 浏览 4 评论 0原文

我经常使用Python的内置随机模块使用任意基于弦的种子来产生具有已知可重复状态的RNG。当然,random.getState()andun.setState()对于保存和恢复RNG的状态很有用,但是实际状态值很笨拙。

是否有一种方法可以从一个状态中得出A String 种子值,当提供给Random.seed()时,会产生一个rng处于与random.setState()的同等调用状态相同的状态

,即给定代码:

>>> import random

>>> random.seed('foo')

>>> state = random.getstate()

>>> random.random()
0.45443115919715416

>>> random.setstate(state)

>>> random.random()
0.45443115919715416

>>> derived_seed = derive_seed(state)

>>> random.seed(derived_seed)

>>> random.random()
0.45443115919715416

>>> print(derived_seed)
<insert derived seed value here... is it an int? a str?>

如何实现上述derive_seed()功能?


更新: random.random()。种子()具有 python实现,将str转换为int int ,而a

更新2:因为处理strbytes种子值所涉及的哈希,因此似乎没有一种逆向工程师的方法来自状态的字符串值。我认为,不过,可以将整数价值倒置。

I frequently use arbitrary string-based seeds with Python's built-in random module to produce RNGs with known, repeatable states. Of course, random.getstate() and random.setstate() are useful for saving and restoring the state of an RNG, but the actual state values are unwieldy.

Is there a way to derive a string seed value from a state that, when provided to random.seed(), produces an RNG in the same state as the equivalent call to random.setstate()?

That is, given the following code:

>>> import random

>>> random.seed('foo')

>>> state = random.getstate()

>>> random.random()
0.45443115919715416

>>> random.setstate(state)

>>> random.random()
0.45443115919715416

>>> derived_seed = derive_seed(state)

>>> random.seed(derived_seed)

>>> random.random()
0.45443115919715416

>>> print(derived_seed)
<insert derived seed value here... is it an int? a str?>

How would you implement the above derive_seed() function?


UPDATE: random.Random().seed() has a Python implementation which converts the str to an int, and a C implementation which converts the integer seed into a byte array. It seems like this process could be reversed to take the state back to a string, but I'm not confident at this level of Python internals.

UPDATE 2: Because of the hashing involved in processing a str or bytes seed value, it doesn't appear that there's a way to reverse engineer a string value from a state. I hold out hope that it's possible to reverse engineer an integer value though.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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