math
CHAPTER 16 / 45
읽기 약 2분
FUNCTION
집합: Set 자료구조의 수학
핵심 개념
합집합·교집합·차집합 — Python set·JavaScript Set의 수학적 기반. 태그 필터링·세그먼트 분류·중복 제거의 본질.
본문
집합 4가지 연산
| 연산 | 기호 | 의미 |
|---|---|---|
| 합집합 | A ∪ B | A 또는 B에 속함 |
| 교집합 | A ∩ B | A와 B 모두에 속함 |
| 차집합 | A − B | A에 있고 B에 없음 |
| 대칭차 | A △ B | 교집합 제외 합집합 |
Python set
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # {1, 2, 3, 4, 5, 6} 합집합
print(A & B) # {3, 4} 교집합
print(A - B) # {1, 2} 차집합
print(A ^ B) # {1, 2, 5, 6} 대칭차
# 부분집합·동등
print({1, 2} <= A) # True (subset)
print({1, 2} < A) # True (proper subset)
print(A == {1, 2, 3, 4}) # True
# O(1) 멤버십 검사 — 리스트보다 빠름
import time
nums = list(range(1_000_000))
nums_set = set(nums)
t0 = time.perf_counter(); 999_999 in nums; t_list = time.perf_counter() - t0
t0 = time.perf_counter(); 999_999 in nums_set; t_set = time.perf_counter() - t0
print(f"list: {t_list*1000:.3f}ms") # ~10ms
print(f"set: {t_set*1000:.3f}ms") # ~0.001ms (10000배+)JavaScript Set
const A = new Set([1, 2, 3, 4]);
const B = new Set([3, 4, 5, 6]);
// 합집합
const union = new Set([...A, ...B]);
// 교집합
const intersect = new Set([...A].filter(x => B.has(x)));
// 차집합
const diff = new Set([...A].filter(x => !B.has(x)));
console.log([...union]); // [1, 2, 3, 4, 5, 6]
console.log([...intersect]); // [3, 4]
console.log([...diff]); // [1, 2]
// ES2025 — Set 메서드
// A.union(B), A.intersection(B), A.difference(B), A.symmetricDifference(B)실전 — 태그 필터링
# 사용자가 선택한 태그와 게시물의 태그가 하나라도 겹치면 표시
def filter_posts(posts, user_tags):
user_set = set(user_tags)
return [p for p in posts if user_set & set(p['tags'])]
posts = [
{'id': 1, 'title': 'React 시작', 'tags': {'react', 'frontend'}},
{'id': 2, 'title': 'PostgreSQL 인덱스', 'tags': {'db', 'backend'}},
{'id': 3, 'title': 'Next.js App Router', 'tags': {'react', 'nextjs'}},
]
result = filter_posts(posts, ['react'])
print([p['title'] for p in result])
# ['React 시작', 'Next.js App Router']실전 — 사용자 세그먼트 분류
# A: Pro 결제 사용자, B: 최근 7일 활성, C: 이메일 인증
pro_users = {1, 2, 3, 4, 5, 6}
active_users = {3, 4, 5, 7, 8, 9}
verified = {1, 3, 4, 8, 10}
# Pro + Active + Verified (3중 교집합) — 핵심 충성 사용자
core = pro_users & active_users & verified
print(core) # {3, 4}
# Pro인데 비활성 (이탈 위험)
churn_risk = pro_users - active_users
print(churn_risk) # {1, 2, 6}
# Active인데 미인증 (마케팅 대상)
marketing = active_users - verified
print(marketing) # {5, 7, 9}실전 — 중복 제거
# 리스트의 중복 제거 + 순서 유지
def unique_ordered(arr):
seen = set()
return [x for x in arr if not (x in seen or seen.add(x))]
arr = [3, 1, 2, 3, 4, 1, 5]
print(unique_ordered(arr)) # [3, 1, 2, 4, 5]
# 단순 중복 제거 (순서 무관)
print(list(set(arr))) # [1, 2, 3, 4, 5]다음 챕터
CH.17 "벤 다이어그램" — 2~3 집합 시각화 + A/B 테스트 사용자 겹침 분석.
AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude
무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6
내 코드의 리스트 멤버십 검사 위치를 분석해서 set 변환 가능한 곳과 예상 성능 향상을 알려줘.
ChatGPT
무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro
한국 SaaS의 사용자 세그먼트 분류 패턴 5가지 사례를 집합 연산 관점에서 비교 분석해줘.
Gemini
무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro
내 사용자 데이터 전체에서 집합 연산으로 발견 가능한 코호트(Pro+Active+Verified 등) Top 10을 시각화해줘.
Grok
무료: Grok 4.1 / SuperGrok $30/mo
2026년 한국 마케팅에서 RFM 세그먼트와 집합 연산 활용 빈도, 실효성을 솔직히 알려줘.
⭐ 이것만 기억하세요
집합: Set 자료구조의 수학은 이 3가지만 확실히 잡으세요
1.집합 연산은 단순 사칙연산이 아닌 코드 자체의 표현 — 합/교/차/대칭차 4가지로 거의 모든 그룹 연산 표현
2.set의 멤버십 검사는 O(1) — 리스트보다 1만 배 이상 빠름. 중복 검사·필터링은 무조건 set으로
3.다음 챕터 CH.17에서 벤 다이어그램으로 2~3 집합의 교차 분석 시각화
공유하기
진행도 16 / 45