gpt4 book ai didi

python - python中 'set.intersection()'的算法是什么?

转载 作者:太空狗 更新时间:2023-10-30 00:40:55 25 4
gpt4 key购买 nike

首先,我的目的是随机获取两个已知集合中的一个元素。所以我原来的方法是先把两个集合相交。然后从相交集中随机选取一个元素。但这是愚蠢的,因为我只需要一个元素而不是一个相交的集合。

所以我需要找到set.intersection()的算法。

我比较了“set.intersection()”和“for{for{}}”方法之间的成本时间。 Set.intersection() 比其他的快(100 倍)。所以使用'for{for{}}'来随机选取元素并不是一个明智的主意。

python 中 set.intersection() 背后的算法是什么?

最佳答案

The algorithm如下:循环较小的集合并复制每个元素,具体取决于它是否在较大的集合中找到。所以,它相当于 C 语言

def intersect(a, b):
if len(a) > len(b):
a, b = b, a

c = set()
for x in a:
if x in b:
c.add(x)
return c

(或者:返回集合(x for x in a if x in b)。)

关于python - python中 'set.intersection()'的算法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20100003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com