🤧
Pythonのset型と集合演算 (HackerRank)
はじめに
HackerRankのpythonコースにて集合演算について学んだ際のことをメモ
set型について
上記記事より
set型のオブジェクトは波括弧{}で生成できる。カンマ区切りで要素を書く。
重複する値は無視されて、一意な値のみが要素として残る。また、setは順序をもたないので、生成時の順序は保持されない。
<例>
s = {3, 1, 2, 2, 3, 1, 4}
print(s)
# {1, 2, 3, 4}
print(type(s))
# <class 'set'>
set型オブジェクトへの要素追加
s = {1, 2, 4}
s.add(8)
print(s) # {8, 1, 2, 4}
和集合.union()or|

.union()の使い方
-
.unionまたは| - 2つのセットオブジェクトの全要素(重複のものは一意になる)
hoge_a = {8, 66, 10, 11}
hoge_b = {4, 2, 66, 8, 11, 3}
result = hoge_a.union(hoge_b)
print(result) # {66, 2, 3, 4, 8, 10, 11}
result = hoge_a | hoge_b
print(result) # {66, 2, 3, 4, 8, 10, 11}
積集合.intersection()or&
問題: Set .intersection() Operation

.intersection()の使い方
-
.intersection()または& - 2つのセットオブジェクトの重複したものが残る。(各要素は一意)
hoge_a = {8, 66, 10, 11}
hoge_b = {4, 2, 66, 8, 11, 3}
result = hoge_a.intersection(hoge_b)
print(result) # {8, 66, 11}
result = hoge_a & hoge_b
print(result) # {8, 66, 11}
差集合.difference()or-
問題: Set .difference() Operation

.difference()の使い方
-
.difference()または- - 重複していない左辺の要素が残る
hoge_a = {8, 66, 10, 11}
hoge_b = {4, 2, 66, 8, 11, 3}
result = hoge_a.difference(hoge_b)
print(result) # {10}
result = hoge_a - hoge_b
print(result) # {10}
対照差集合.symmetric_difference()or^
問題: Set .symmetric_difference() Operation

.symmetric_difference()の使い方
-
.symmetric_difference()または^ - 重複していない互いの要素が残る
hoge_a = {8, 66, 10, 11}
hoge_b = {4, 2, 66, 8, 11, 3}
result = hoge_a.symmetric_difference(hoge_b)
print(result) # {2, 3, 4, 10}
result = hoge_a ^ hoge_b
print(result) # {2, 3, 4, 10}
Discussion