如何从python and.getState()中得出便携式种子?
我经常使用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:因为处理str
或bytes
种子值所涉及的哈希,因此似乎没有一种逆向工程师的方法来自状态的字符串值。我认为,不过,可以将整数价值倒置。
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 技术交流群。

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