cmod.ify
[11723] 집합 본문
728x90
반응형
틀린 코드
m = int(input())
answer = set()
setting = {i for i in range(1,21)}
for _ in range(m):
temp = input()
if "add" in temp:
num = int(temp.split()[1])
answer.add(num)
elif "remove" in temp:
num = int(temp.split()[1])
if num in answer:
answer.remove(num)
elif "check" in temp:
num = int(temp.split()[1])
if num in answer:
print(1)
else: print(0)
elif "toggle" in temp:
num = int(temp.split()[1])
if num not in answer:
answer.add(num)
else:
answer.remove(num)
elif "all" in temp:
answer = setting
elif "empty" in temp:
answer.clear()
틀린 이유:
1. 입력 속도가 느림 > stdlin으로 속도 향상
2. 매번 입력 받고 in 키워드로 탐색함. in키워드는 문자를 하나씩 비교함
- > 미리 split해서 변수에 저장
2. copy를 얕은 복사를 해서 원본 침해 우려
(출처 : Gemini)
정답코드
import sys
input = sys.stdin.readline
m = int(input())
answer = set()
setting = {i for i in range(1,21)}
for _ in range(m):
line = input().split()
command = line[0]
if command == "add":
answer.add(int(line[1]))
if command == "remove":
answer.discard(int(line[1]))
elif command == "check":
if int(line[1]) in answer:
print(1)
else: print(0)
elif "toggle" == command:
if int(line[1]) not in answer:
answer.add(int(line[1]))
else:
answer.discard(int(line[1]))
elif "all" == command:
answer = setting.copy()
elif "empty" == command:
answer.clear()728x90
반응형
'BASIC > 코딩테스트' 카테고리의 다른 글
| [11047] 동전0 (0) | 2025.12.19 |
|---|---|
| [1764] 듣보잡 (0) | 2025.12.19 |
| [1620] 나는야 포켓몬 마스터 이다솜 (0) | 2025.12.18 |
| [코드트리] 체크 다이아몬드 (2) | 2023.10.24 |
| [코드트리] 두 개의 직각삼각형 (0) | 2023.10.22 |