[알고리즘/백준] 11723번 : 집합(python)

유현민·2022년 5월 2일
0

알고리즘

목록 보기
161/253

시간을 줄이기 위해서 꼭 readline()을 써야한다. 안쓰면 시간초과 나옴...

python에서 집합은 set()을 사용하면 된다.

또한 discard(x)는 만약 x가 집합 안에 있으면 삭제하고 없으면 무시하고 넘어간다.
remove(x)를 쓰면 x가 집합 안에 없으면 오류를 출력한다.

명령어도 clear, all은 숫자가 들어오지 않기 때문에 길이로 구별하여 코딩을 해준다.

import sys

M = int(sys.stdin.readline())
S = set()
for _ in range(M):
    comm = sys.stdin.readline().split()
    if len(comm) == 2:
        x = int(comm[1])
        if comm[0] == "add":
            S.add(x)
        elif comm[0] == "remove":
            S.discard(x)
        elif comm[0] == "toggle":
            S.remove(x) if x in S else S.add(x)
        else:
            print(1 if x in S else 0)
    else:
        if comm[0] == 'all':
            S = set([i for i in range(1, 21)])

        else:
            S.clear()


profile
smilegate megaport infra

0개의 댓글