How to get the intersection between two sets in python ?

Published: November 20, 2020

Tags: Python;

DMCA.com Protection Status

Example of how to calculate the intersection between two sets in python

Intersection between two sets

Lets consider two sets:

s1 = {1,2,3,4,5,6}
s2 = {4,5,6,7,8,9}

To get the Intersection between s1 and s2, a solution is to use intersection():

intersection_set = s1.intersection(s2)

print(intersection_set)

which returns here

{4, 5, 6}

source <a href=Intersection (mathématiques)">
source Intersection (mathématiques)

Calculate the probability of the intersection of events s1 and s2

import random

n = 100

n_intersection = 0
for i in range(100):
    r1 = random.sample(s1, 1)[0]
    r2 = random.sample(s2, 1)[0]
    if {r1,r2}.issubset(intersection_set): n_intersection += 1

print(n_intersection/n)

returns for example

0.27

References

Image

of