1. 배열 index 구하기
1-1 최대값이 중복인 경우 맨 앞의 인덱스를 반환한다.
score = [10,2,4,5,9, 10]
print(score.index(max(score)))
#출력 : 0
1-2 배열의 최대값의 인덱스 다중으로 구하기
score = [10,2,4,5,9, 10]
answer = list(filter(lambda x: score[x] == max(score), range(len(score))))
print(answer)
# 출력: [0, 5]
1-3 배열 맨 마지막 index
test = [1,4,5,6]
print(test[-1])
# 출력 : 6
2. 배열에 추가
2-1 맨 뒤에 삽입
list = [2, 9, 3]
list.append(7)
print(list)
# 출력 : [2, 9, 3, 7]
2-2 원하는 위치에 삽입
-1에 넣으면 의외로 맨 뒤가 아닌 맨뒤에서 한칸 앞에 들어간다.
list = [2, 9, 3]
list.insert(0, 50)
list.insert(-1, 100)
print(list)
# 출력 : [50, 2, 9, 100, 3]
3. 배열 삭제
3-1 특정 값 삭제
a = [1, 2, 3, 4, 5, 6, 7]
a.remove(3)
print(a)
# 출력 [1, 2, 4, 5, 6, 7]
# 값이 없는경우 오류 발생
a.remove(9)
# 출력
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
3-2 특정 index 삭제
a = [1, 2, 3, 4, 5, 6, 7]
del a[1]
print(a)
# 출력 [1, 3, 4, 5, 6, 7]
3. 정렬
3-1 이차원 배열 첫번째 원소로 오름차순 정렬
tickets = [[2, 1], [3, 4], [1, 2], [1, 3], [3, 2]]
tickets.sort(key=lambda x:x[0])
print(tickets)
# 출력 [[1, 2], [1, 3], [2, 1], [3, 4], [3, 2]]
3-2 이차원 배열 두가지 원소 사용해 오름차순 정렬
tickets = [[2, 1], [3, 4], [1, 2], [1, 3], [3, 2]]
tickets.sort(key=lambda x: (x[0], -x[1]))
3-2 배열 역순으로 돌리기
+ 배열 string으로 변환
alpha=['A','B','C','D','E']
alpha.reverse()
print(alpha)
#출력 : ['E', 'D', 'C', 'B', 'A']
str_alpha = ''.join(alpha)
print(str_alpha)
#출력 : EDCBA
4. 큐
4-1 기본적인 큐 사용법 ( deque )
from collections import deque
queue = deque([4, 5, 6])
queue.append(7)
queue.append(8)
print(queue)
# 출력 : deque([4, 5, 6, 7, 8])
queue.popleft()
queue.popleft()
print(queue)
#출력 deque([6, 7, 8])
4-1 우선순위 큐 사용법
from queue import PriorityQueue
queue = PriorityQueue()
queue.put((0, 'a'))
cost,now = queue.get()
4-2 heapq
priorityQueue는 스레드 세이프
heapq는 스레드 세이프 하지 않은 대신 좀더 빠름
코테에서는 heapq사용이 유리하다.
heapq의 기본은 min heap이다.
기본 사용법
import heapq
heap = []
heapq.heappush(heap, 4)
heapq.heappush(heap, 1)
heapq.heappush(heap, 7)
heapq.heappush(heap, 3)
print(heap)
# 출력 : [1, 3, 7, 4]
기존 list를 heapq로 변환
import heapq
heap = [4, 1, 7, 3, 8, 5]
heapq.heapify(heap)
print(heap)
# 출력 : [1, 3, 5, 4, 8, 7]
max heap 사용
from heapq import heappush, heappop
nums = [4, 1, 7, 3, 8, 5]
heap = []
for num in nums:
heappush(heap, (-num, num))
Custom 연산자 만들기
x 오름차순, y는 내림차순으로 정렬하고 싶을 때
import heapq
# x 오름차순
# y 내림차순
class node:
def __init__(self, x, y):
self.x = x
self.y = y
## less then self < other 를 판단하는 기준을 정의
def __lt__(self, other):
if self.x == other.x:
return self.y > other.y
else :
return self.x < other.x
def __str__(self):
return 'x: {}, y: {}'.format(self.x, self.y)
heap = []
heapq.heappush(heap, node(7, 3))
heapq.heappush(heap, node(3, 5))
heapq.heappush(heap, node(3, 6))
heapq.heappush(heap, node(2, 10))
heapq.heappush(heap, node( 7, 5 ))
while heap:
print(heapq.heappop(heap))
# 출력 :
# x: 2, y: 10
# x: 3, y: 6
# x: 3, y: 5
# x: 7, y: 5
# x: 7, y: 3
5. 문자열
5 -1 문자열 리스트로 변환
str ="RVRR.U"
str_list = list(str)
print(str_list)
# 출력 : ['R', 'V', 'R', 'R', '.', 'U']
6. 딕셔너리
6-1 . defaultdict
defaultdict을 사용하면 dict 에 있는지 없는지 확인해서 배열 초기화 해주는 귀찮은 일을 안해도 된다.
W ="superaquatornado"
from collections import defaultdict
word_dict = defaultdict(list)
for i in range(len(W)):
word_dict[W[i]].append(i)
print(word_dict)
# 출력
{'s': [0], 'u': [1, 7], 'p': [2], 'e': [3], 'r': [4, 11], 'a': [5, 8, 13], 'q': [6], 't': [9], 'o': [10, 15], 'n': [12], 'd': [14]})
7. min, max
7-1 . min(arg1, arg2)
print(min(10, 20))
# 출력 : 10
8. 형변환
8-1 string to int
a = "1000"
print(type(a), a )
b = int(a)
print(type(b) , b)
# 출력
#<class 'str'> 1000
#<class 'int'> 1000
9. 전역 변수
answer = 0
def dfs(depth, now, numbers, target):
# global 변수를 사용한다고 선언해 줘야 한다.
global answer
if depth == len(numbers):
if target == now :
answer += 1
return
for i in dir:
dfs(depth +1, now + i * numbers[depth], numbers, target)
def solution(numbers, target):
dfs(0, 0, numbers, target)
return answer
'백준' 카테고리의 다른 글
[백준 14719] 빗물 (python) (0) | 2023.04.28 |
---|---|
[백준 4485] 녹색 옷 입은 애가 젤다지? (python) (1) | 2023.04.20 |
[백준 1806] 부분합 (python) (0) | 2023.04.06 |
[백준 1987] 알파벳 (python) (0) | 2023.04.05 |
[백준 25757] 임스와 함께하는 미니게임 python(시간초과) (0) | 2023.01.04 |