数学的演算 パート1
CoddyのPythonジャーニー「Logic & Flow」セクションの一部。レッスン 33/78。
集合は、union、intersection、difference、symmetric difference などの数学的な演算をサポートしています。これらの演算は、さまざまな方法で集合を比較したり組み合わせたりするのに役立ちます。
Union(| または union()):重複を除外し、両方の集合の要素を組み合わせます。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set)
# 出力: {1, 2, 3, 4, 5}共通部分(& または intersection()):両方の集合に共通する要素だけを含む集合を返します。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2
print(intersection_set)
# 出力: {3}差分(- または difference()):1つ目の集合に含まれているが、2つ目の集合には含まれていない要素を含む集合を返します。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2
print(difference_set)
# 出力: {1, 2}対称差分(^ または symmetric_difference()):どちらか一方の集合には含まれるが、両方には含まれない要素を含む集合を返します。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set)
# 出力: {1, 2, 4, 5}チャレンジ
簡単set1 と set2 の2つの集合を引数として受け取る、set_operations という名前の関数を作成してください。この関数では、次の操作を実行します。
set1とset2の union を Calculate します。set1とset2の intersection を Calculate します。set1とset2の difference(set1に含まれ、set2には含まれない要素)を Calculate します。set1とset2の symmetric difference を Calculate します。- これらの操作の results を containing する dictionary を Return します。キーは
"union"、"intersection"、"difference"、"symmetric_difference"です。
自分で試してみよう
def set_operations(set1, set2):
# 以下の各空のセットを正しいセット演算に置き換えてください
# 和集合を計算する
union_result = set()
# Calculate the intersection
intersection_result = set()
# 差集合を計算する
difference_result = set()
# Calculate the symmetric difference
symmetric_difference_result = set()
# 結果を含む辞書を返す
return {
"union": union_result,
"intersection": intersection_result,
"difference": difference_result,
"symmetric_difference": symmetric_difference_result
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Logic & Flowのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ