Python - [백준]11723-이진수 연산

Paek·2023년 2월 1일
0

코테공부

목록 보기
16/44

출처

https://www.acmicpc.net/problem/11723

문제

다양한 집합 연산을 처리하는 문제이다.

풀이

파이썬의 집합 연산자 set()를 사용해서 문제를 풀면 된다.
add, discard를 사용하여 문제를 해결하면 된다. remove 대신 discard를 사용하는 이유는, 삭제하려는 원소가 집합 내에 존재 하지 않으면 remove는 에러를 출력하지만 discard는 예외처리를 통해 에러를 출력하지 않는다.

코드

import sys
input = sys.stdin.readline

n  = int(input())
s = set()

for _ in range(n):
    a = input().strip().split()
    if len(a) == 1:
        if a[0] == "all":
            s = set([i for i in range(1, 21)])
        else:
            s = set()
    else:
        x = int(a[1])
        if a[0] == "add":
            s.add(x)
        elif a[0] == "remove":
            s.discard(x)
        elif a[0] == "check":
            print(1 if x in s else 0)
        elif a[0] == "toggle":
            if x in s:
                s.discard(x)
            else:
                s.add(x)
        
profile
티스토리로 이전했습니다. https://100cblog.tistory.com/

0개의 댓글