입출력
1) 입력을 나누어 받기
a, b = map(int, input().split())
- 첫 번째 줄에는 입력되는 숫자들의 줄 수가 주어지고, 다음 줄 부터 숫자들이 공백을 기준으로 주어짐
for i in range(int(input())):
inputStr = input()
arr = list(inputStr)
MAP.append(arr)
MAP = [list(map(int, input().split())) for _ in range(int(input()))]
- 정수와 배열이 같은 줄에 입력으로 들어오는 경우
N, *arr = map(int, input().split())
2) 입출력 가속
from sys import stdin, stdout
input = stdin.readline
print = stdout.write
3) 문자열 한 글자씩 저장
"""
입력 예시
3
AAAA
ABCA
AAAA
"""
arr = [input() for _ in range(N)]
arr = [list(input()) for _ in range(N)]
alph = "ABCD"
alph[::-1]
배열
1) 배열 연결
arr = [1, 2, 3, 4]
arrToString = ''.join(map(str, arr))
print(arr*)
print(arrToString)
2) 최대 범위 설정
- 최대 범위를 정하기 애매한 상황에 큰 값을 설정하는 방법
import sys
ans = sys.maxsize
for num in arr:
if ans > num:
ans = num
3) 배열 초기화
- N : 배열 가로 크기, M : 배열 세로 크기
N, M = map(int, input().split())
arr = [[0] * N for _ in range(M)]
B = int(input())
arr = list(map(int, list(str(B))))
arr = [int(i) for i in str(B)]
4) 배열 원소 개수
list.count(1)
str.count(0)
5) 배열 중복 제거
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'c', 'd' ]
alpha = list(set(alpha))
lst = [[1,2], [1,2], [1]]
list(set(map(tuple, lst)))
6) Counter
from collections import Counter
arr = [int(input()) for _ in range(10)]
"""
3
7
8
7
7
9
3
0
7
3
"""
print(sum(arr) // 10)
val = Counter(arr).most_common()
print(val)
print(val[0][0])
진법 변환
1) 10진수 -> 2, 8, 16진수로 변환
bin(42)
oct(42)
hex(42)
2) 2, 8, 16진수 -> 10진수로 변환
int('0b101010', 2)
int('0o52', 8)
int('0x2a', 16)
3) 2진수 덧셈
A = 1001101
B = 10010
result = bin(A) + bin(B)
삼항 연산자
if a > b:
res = a
else:
res = b
res = a if a > b else b
정렬
1) 배열 정렬
- 길이가 짧은 것부터, 길이가 같으면 사전 순으로
- 조건에 따라 정렬하여 단어 출력, 단 같은 단어가 여러 번 입력된 경우에는 한 번만 출력
data_list = ['but','i','wont','hesitate','no','more','no','more','it','cannot','wait','im','yours']
data_list = list(set(data_list))
data_list.sort()
data_list.sort(key = lambda x : len(x))
2) 2차원 리스트 정렬
a = [(1,2), (0,1), (5,1), (5,2), (3,0)]
b = sorted(a)
c = sorted(a, key = lambda x : x[0])
d = sorted(a, key = lambda x : x[1])
e = [(1, 3), (0, 3), (1, 4), (1, 5), (0, 1), (2, 4)]
f = sorted(e, key = lambda x : (x[0], -x[1]))
조합과 순열
1) 조합
from itertools import combinations
list(combinations([1, 2, 3], 2))
2) 순열
from itertools import permutations
list(permutations([1, 2, 3], 2))
Heap
import heapq
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 2)
heapq.heappush(heap, 5)
heapq.heappush(heap, 7)
print(heap)
print(len(heap))
heapq.heappop(heap)
print(heap)
double-ended queue (dequeue)
- FIFO + LIFO 연산 모두 가능 -> 양방향에서 데이터 처리 가능
- stack과 queue도 시간 초과를 방지하기 위해 deque를 사용해서 구현
from collections import deque
deq = deque()
deq = deque([i for i in range(1, 5)])
deq.appendleft(10)
deq.append(11)
print(deq.pop())
print(deq.popleft())
deq.rotate(-1)
deq.rotate(1)
deq.rotate(2)
Priority Queue
from queue import PriorityQueue
que = PriorityQueue()
que.put(2)
que.put(1)
que.put(3)
print(que.queue)
print(que.get())
print(que.queue)