백준 | 집합

justhaza.log·2025년 1월 28일

알고리즘: BOJ

목록 보기
113/125

백준 집합


주어진 조건에 따라 분기 처리하면 된다.

import sys

m = int(sys.stdin.readline())
s = set()

for _ in range(m):
    operation = sys.stdin.readline().split()

    if operation[0] == "add":
        if int(operation[1]) not in s:
            s.add(int(operation[1]))
    elif operation[0] == "remove":
        if int(operation[1]) in s:
            s.remove(int(operation[1]))
    elif operation[0] == "check":
        if int(operation[1]) in s:
            print(1)
        else:
            print(0)
    elif operation[0] == "toggle":
        if int(operation[1]) in s:
            s.remove(int(operation[1]))
        else:
            s.add(int(operation[1]))
    elif operation[0] == "all":
        s = set(range(1, 21))
    elif operation[0] == "empty":
        s = set()

Python의 set 자료형에서 특정 값을 제거하는 메서드는 remove와 discard가 있다.

존재하지 않는 값을 제거하려고 할 때, remove()는 KeyError가 발생하지만, discard()는 아무 작업도 하지 않아 KeyError가 발생하지 않는다.

discard()를 활용한 코드는 다음과 같다.

import sys

m = int(sys.stdin.readline())
s = set()

for _ in range(m):
    operation = sys.stdin.readline().split()

    if operation[0] == "add":
        s.add(int(operation[1]))
    elif operation[0] == "remove":
        s.discard(int(operation[1]))
    elif operation[0] == "check":
        if int(operation[1]) in s:
            print(1)
        else:
            print(0)
    elif operation[0] == "toggle":
        if int(operation[1]) in s:
            s.discard(int(operation[1]))
        else:
            s.add(int(operation[1]))
    elif operation[0] == "all":
        s = set(range(1, 21))
    elif operation[0] == "empty":
        s = set()
profile
알고리즘이나 SQL 문제 풀이를 올리고 있습니다. 피드백 환영합니다!

0개의 댓글