sách gpt4 ăn đã đi

python - `random.random` chạy nhanh hơn khi sử dụng `random.shuffle` làm đối số từ khóa trong Python3

In lại 作者:太空狗 更新时间:2023-10-29 21:07:33 28 4
mua khóa gpt4 giày nike

我只是观察到,当使用 Python3 时,使用 random.shuffle 对列表进行洗牌需要大约一半的运行时间,而当为 显式提交函数 random.random >random 关键字参数。我检查了Python2是否有同样的问题,发现它只出现在Python3。

我使用下面的代码来测量两个版本的运行时间:

from timeit import Timer
t1 = Timer("random.shuffle(l)", "import random; l = list(range(100000))")
t2 = Timer("random.shuffle(l, random = random.random)", "import random; l = list(range(100000))")
print("With default rand: %s" % t1.repeat(10,1))
print("With custom rand: %s" % t2.repeat(10,1))

我做了一个testcase at ideone供您使用 Python3 和 Python2 查看相同的代码.

theodocumentation for shuffle当我省略可选的关键字参数 ngẫu nhiên 时,在默认情况下使用相同的函数 random.random,所以当我给它相同的函数来生成时应该没有区别默认情况下的随机数。

我检查了 Lib/random.py 文件夹中的 shuffle 函数的相应来源(Python2 与 Python3),发现它们的行为方式相同 nếu như 我明确调用带有 ngẫu nhiên 关键字函数的 Python3 版本。如果我省略这个参数,Python3 将使用辅助函数 _randbelow 所以应该是我的问题的根源。我不明白为什么 Python3 使用 _randbelow 因为它减慢了 shuffle 的速度。据我所知,它的好处在于生成任意大的随机数,但它不应该减慢我对少于 2^32 个元素(在我的例子中是 100000 个)的列表的改组。

任何人都可以向我解释为什么我在运行时看到如此不同,尽管当我使用 Python3 时它们应该更接近吗?

P.S.:请注意,我不感兴趣为什么使用 Python2 的运行时比使用 Python3 更好,但是在 Python3 中使用参数 rand=rand.rand 参数与不使用参数时的运行时差异仅适用于 Python3。

câu trả lời hay nhất

random.shuffle 函数中的文档字符串与代码相矛盾。在 python 2.7.2+ 中,文档字符串是正确的:

    def shuffle(self, x, random=None, int=int):
"""x, random=random.random -> shuffle list x in place; return None.

Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.
"""

if random is None:
random = self.random
for i in reversed(xrange(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = int(random() * (i+1))
x[i], x[j] = x[j], x[i]

但是在 Python 3.2 中我们发现:

def shuffle(self, x, random=None, int=int):
"""x, random=random.random -> shuffle list x in place; return None.

Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.
"""

randbelow = self._randbelow
for i in reversed(range(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = randbelow(i+1) if random is None else int(random() * (i+1))
x[i], x[j] = x[j], x[i]

所以docstring还是老样子,不过现在使用的默认函数是random.randbelow

关于python - 在 Python3 中使用 `random.shuffle` 作为关键字参数时 `random.random` 的运行时间更短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15117573/

28 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress