[python vs Java] 집합 자료형 set에서 교집합, 합집합, 차집합 구하기

박현아·2025년 5월 19일
0

Python

목록 보기
2/6

집합 자료형인 set의 특징은

  • 중복을 허용하지 않는다
  • 순서가 없다

✔️ 파이썬, 자바로 교집합, 합집합, 차집합 구하기

Python 🐍

a = {1, 2, 3}
b = {2, 3, 4}

print(a & b) 
print(a.intersection(b))  # 교집합: {2, 3}
print(a | b) 
print(a.union(b))         # 합집합: {1, 2, 3, 4}
print(a - b) 
print(a.difference(b))    # 차집합: {1}

Java ☕️

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 3));
        Set<Integer> b = new HashSet<>(Arrays.asList(2, 3, 4));

        // 교집합
        Set<Integer> intersection = new HashSet<>(a);
        intersection.retainAll(b);
        System.out.println("교집합: " + intersection);  // [2, 3]

        // 합집합
        Set<Integer> union = new HashSet<>(a);
        union.addAll(b);
        System.out.println("합집합: " + union);         // [1, 2, 3, 4]

        // 차집합
        Set<Integer> difference = new HashSet<>(a);
        difference.removeAll(b);
        System.out.println("차집합: " + difference);    // [1]
    }
}

이렇게 비교해보니 코드 길이 차이가... 😱 파이썬이 훨씬 간단하고 쉽긴 하다 !!

0개의 댓글