Sada Python | rozdiel()
Rozdiel medzi týmito dvoma sadami v Pythone sa rovná rozdielu medzi počtom prvkov v dvoch sadách. Funkcia different() vracia množinu, ktorá je rozdielom medzi dvoma množinami. Skúsme zistiť, aký bude rozdiel medzi dvoma množinami A a B. Potom (množina A – množina B) budú prvky prítomné v množine A, ale nie v B a (množina B – množina A) budú prvky prítomné v súprave B, ale nie v súprave A.
Príklad:
set A = {10, 20, 30, 40, 80} set B = {100, 30, 80, 40, 60} set A - set B = {10, 20} set B - set A = {100, 60} Explanation: A - B is equal to the elements present in A but not in B B - A is equal to the elements present in B but not in A Pozrime sa na Vennov diagram nasledujúcej funkcie množiny rozdielov.
Syntax:
set_A.difference(set_B) for (A - B) set_B.difference(set_A) for (B - A)
V tomto programe sa pokúsime zistiť rozdiel medzi dvoma sadami set_A a set_B, a to v oboch smeroch:
Python3
# Python code to get the difference between two sets> # using difference() between set A and set B> # Driver Code> A> => {> 10> ,> 20> ,> 30> ,> 40> ,> 80> }> B> => {> 100> ,> 30> ,> 80> ,> 40> ,> 60> }> print> (A.difference(B))> print> (B.difference(A))> |
Výkon:
{10, 20} {100, 60} Na nájdenie rozdielu medzi dvoma množinami môžeme použiť aj operátor –.
Python3
# Python code to get the difference between two sets> # using difference() between set A and set B> # Driver Code> A> => {> 10> ,> 20> ,> 30> ,> 40> ,> 80> }> B> => {> 100> ,> 30> ,> 80> ,> 40> ,> 60> }> print> (A> -> B)> print> (B> -> A)> |
Výkon:
{10, 20} {100, 60} Ak máme rovnaké množiny, vráti nulovú množinu.
Python3
# Python code to get the difference between two sets> # using difference() between set A and set B> # Driver Code> A> => {> 10> ,> 20> ,> 30> ,> 40> ,> 80> }> B> => {> 10> ,> 20> ,> 30> ,> 40> ,> 80> ,> 100> }> print> (A> -> B)> |
Výkon:
set()