[Python] SET() 전용 집합 메서드

Gi Woon Lee·2024년 10월 2일
0

TIL

목록 보기
69/78

TIL: Python set 전용 집합 메서드

학생 때 배웠던 집합 연산은 파이썬에서도 가능하다. SET 타입은 수학의 집합을 표현하는 방식으로 중복을 허용하지 않으며 집합 연산을 쉽게 수행할 수 있도록 설계되어 있다.

  1. 교집합 (intersection)

    • 두 집합의 공통된 요소를 반환
    • 사용법:
      • set1.intersection(set2)
      • 또는 set1 & set2
    • 예시:
      set1 = {1, 2, 3}
      set2 = {2, 3, 4}
      result = set1.intersection(set2)  # 결과: {2, 3}
  2. 합집합 (union)

    • 두 집합의 모든 요소를 반환 (중복 제거).
    • 사용법:
      • set1.union(set2)
      • 또는 set1 | set2
    • 예시:
      set1 = {1, 2, 3}
      set2 = {3, 4, 5}
      result = set1.union(set2)  # 결과: {1, 2, 3, 4, 5}
  3. 차집합 (difference)

    • 첫 번째 집합에만 있고, 두 번째 집합에는 없는 요소를 반환
    • 사용법:
      • set1.difference(set2)
      • 또는 set1 - set2
    • 예시:
      set1 = {1, 2, 3}
      set2 = {2, 3, 4}
      result = set1.difference(set2)  # 결과: {1}
  4. 대칭 차집합 (symmetric_difference)

    • 두 집합 중 한쪽에만 있는 요소를 반환
    • 사용법:
      • set1.symmetric_difference(set2)
      • 또는 set1 ^ set2
    • 예시:
      set1 = {1, 2, 3}
      set2 = {3, 4, 5}
      result = set1.symmetric_difference(set2)  # 결과: {1, 2, 4, 5}

참고문제

def solution(lottos, win_nums):
    rank = {6: 1, 5:2, 4:3, 3:4, 2:5, 1:6, 0:6}
    
    count_zero = lottos.count(0)
    
    matched_num = len(set(lottos) & set(win_nums))
    
    max_rank = rank[matched_num + count_zero]
    min_rank = rank[matched_num]
    
    return [max_rank, min_rank]

0개의 댓글