【发布时间】:2016-08-14 14:09:41
【问题描述】:
我正在编写一个兼容 Python 2.7 和 3.5 的程序。它的某些部分依赖于随机过程。我的单元测试使用任意种子,这会导致跨执行和语言的结果相同...除了使用 random.shuffle 的代码。
Python 2.7 中的示例:
In[]: import random
random.seed(42)
print(random.random())
l = list(range(20))
random.shuffle(l)
print(l)
Out[]: 0.639426798458
[6, 8, 9, 15, 7, 3, 17, 14, 11, 16, 2, 19, 18, 1, 13, 10, 12, 4, 5, 0]
Python 3.5 中的相同输入:
In []: import random
random.seed(42)
print(random.random())
l = list(range(20))
random.shuffle(l)
print(l)
Out[]: 0.6394267984578837
[3, 5, 2, 15, 9, 12, 16, 19, 6, 13, 18, 14, 10, 1, 11, 4, 17, 7, 8, 0]
注意伪随机数是一样的,但是打乱的列表是不同的。正如预期的那样,重新执行单元不会改变它们各自的输出。
如何为两个版本的 Python 编写相同的测试代码?
【问题讨论】:
-
另外,快速浏览 Py2 implementation 和 Py3 implementation 表明 shuffle 本身有不止一种实现(尽管它们可能是等效的 - 我希望应该有一个单元测试引入了修改)。
-
尝试
random.seed(42, version=1)(或者可能是版本=2;但设置此参数),如记录的here。 -
[random.random() for _ in range(20)]确实在两个版本上返回相同的结果 - 所以看起来这是random.shuffle的实现更改... -
@sascha 在直接使用
int作为种子时不相关。 -
@sascha 在 Py3 下输出相同,
unexpected keyword argument在 Py2 下输出。
标签: python python-2.7 python-3.x shuffle random-seed