Channi Studies

[ADT] Set - 2 | Set Opeartions 본문

Data Science/Data Structure & Algorithm

[ADT] Set - 2 | Set Opeartions

Chan Lee 2025. 5. 15. 04:23

Union, Intersection, and Difference

If you are familiar with set notations from your math course, than you would know all these already. 

The union of sets X and Y, denoted as X ∪ Y, is a set that contains every element from X, every element from Y, and no duplicates. 

The intersection of sets X and Y, denoted as X ∩ Y, is a set that contains every element that is in both X and Y, no duplicates. 

The difference of sets X and Y, denoted as X \ Y, is a set that contains every element that is in X but not in Y, no duplicates. 

The union and intersection opeartions are commutative, meaning X ∪ Y = Y ∪ X, and X ∩ Y = Y ∩ X. Difference is not a commutative operation. 

 


Filter and Map

filter operation on set X produces a subset containing only elements from X that satisfy a particular condition. The condition for filtering is commonly represented by a filter predicate: A function that takes an element as an argument and returns a Boolean value indicating whether or not that element will be in the filtered subset. 

map oepartion on X produces a new set by applying some function F to each element. (Ex. If X = {18, 44, 38, 6} and F is a function that divides a value by 2, then SetMap(X, F) = {9, 22, 19, 3})




Static and Dynamic Set Opeartions

dynamic set is a set that can change after being constructed. A static set is a set that doesn't change after being constructed.

A collection of elements is commonly provided during construction of a static set, each of which is added to the set. (Ex. A static set constructed from the list of integers {19, 67, 77, 67, 59, 19} will be {19, 67, 77, 59})

 

Static sets support most set opeartions by returning a new set representing the operation's result. The table below summarizes the common opeartions for each set.

Static and Dynamic Set Opeartions

Basically the main difference is that static can't add/remove an element after creation, but dyanmic can. Other opeartions at the below are all possible because they don't modify the original set, but create and return a new set. 

 

현실에서 Static 또는 Dynamic set을 선택하는 것은 간단합니다. 데이터셋에 변화가 필요하면 dynamic, 그렇지 않다면 static 입니다.

예를 들어 우리의 프로그램에 전 세계의 모든 국가 리스트를 set 형태로 저장한다고 합시다. 이 때에는 물론 다양한 변수로 국가가 추후에 생성 또는 소멸될 가능성도 있지만, 일반적으로 국가는 장기간에 걸쳐 존재하기 때문에 static을 활용할 것 입니다. 

원소 주기율표가 필요한 프로그램에서 셋을 사용한다고 해도, 새로운 원소가 발견된 가능성이 존재하지 않는건 물론 아니지만, 역시나 일반적으로 큰 변화가 존재하지 않을 것이기에 static을 활용합니다. 

반면 일반적인 고객 데이터를 관리할 때 set을 사용한다고 해봅시다. 이 때에는 매우 빈번하게 새로운 고객의 정보 또한 추가되어야 할 것이고, 회원 탈퇴라던가 특정 절차에 의해서 기존의 고객 정보를 제거해야 하는 경우도 비일비재 할 것입니다. 이러한 경우에는 자연스럽게 dynamic set을 채택하는 것이 옳겠죠?