Python中“ set.intersection()”的算法是什么? [英] What's the algorithm of 'set.intersection()' in python?

查看:212
本文介绍了Python中“ set.intersection()”的算法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

First of all, my purpose is to randomly get only one element in both known sets. So my original method is firstly intersect two sets. And then randomly pick up a element from the intersected set. But this is foolish, because that I only need a elements but a intersected set.

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

So I need to find the algorithm of set.intersection().

我比较了 set.intersection()和 for {for {}}的方法。 Set.intersection()比其他方法快100倍。因此,使用 for {for {}}来随机选择元素不是一个明智的主意。

I compare the cost time between the methods of 'set.intersection()' and 'for{for{}}'. Set.intersection() is more faster than other one(100 times). So using 'for{for{}}' to pick up a randomly elements is not a wise idea.

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

What's the algorithm behind set.intersection() in python?

推荐答案

算法如下:较小的集合被循环遍历,并且根据是否在较大的集合中找到每个元素,将其复制。因此,它等于C的

The algorithm is as follows: the smaller set is looped over and every element is copied depending whether it's found in the bigger set. So, it's the C equivalent of

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

(或: return set(x表示x如果a中的x表示x)。)

这篇关于Python中“ set.intersection()”的算法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆