주어진 조건에 따라 분기 처리하면 된다.
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()