나를 위해 쓰는 코테전 봐야할 파이썬 알고리즘 풀 때 알아야 할 것!
1. 입력받기
input으로 받기
N = int(input())
A, B = map(int, input().split())
a_list = list(map(int, input().split()))
sys.stdin.readlines 사용하기
import sys
member_list = sys.stdin.readlines()[1:]
import sys
n = int(input())
# 여러줄의 숫자를 한번에 입력받아서 숫자 배열로 바꾸기
lines = list(map(int, sys.stdin.readlines()))
2. Dictionary(Map) 사용하기.
자바, JS로 코딩테스트할 때 많이 사용하는 Map.
파이썬에서는 dictionary이다. 내부적으로 hash map으로 구현되어있어 접근 할 때 시간복잡도가 O(1)이다.
마찬가지로 key-value 로 이루어져있고
생성은 간단히 new_dict = {}
로 하면 된다.
js와의 차이점은 js는 전개연산자로 접근이 되지만 파이썬은 아니다
따라서 무조건 배열처럼 접근해야 한다.
아래는 Dictionary를 사용한 코드이다.
# https://www.acmicpc.net/problem/10816
# dict을 사용하여 쉽게 풀이
import sys
input = sys.stdin.readline
N = int(input())
card_list = list(map(int, input().split()))
M = int(input())
target_list = list(map(int, input().split()))
card_set = {}
for card in card_list:
if card in card_set:
card_set[card] += 1
else:
card_set[card] = 1
answer = []
for target in target_list:
if target in card_set:
answer.append(str(card_set[target]))
else:
answer.append("0")
print(" ".join(answer))
'Study > Algorithms' 카테고리의 다른 글
백준 10866: 덱 (Python) (0) | 2024.05.31 |
---|---|
백준 10816 숫자 카드 2 (Python) (0) | 2024.05.31 |
백준 10814: 나이순 정렬 (0) | 2024.05.31 |
백준 10871 X보다 작은 수 (Python) (0) | 2024.05.30 |
백준 10809: 알파벳 찾기 (Python) (0) | 2024.05.30 |