stack overflow란?

while(alive){ code();

코딩테스트

꼭 알아야하는 코딩테스트 기초 알고리즘

나가니 2023. 2. 8. 23:13

List Comprension

n,m=3,4
array = [[0]*m for _ in range(n)]

array

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

 

List Method

.append()
.sort()
.reverse()
.insert()
.count()
.remove()

 

Dictionary

data = dict()


.keys()
.values()

 

set

data = set() or data = {}
.add() # 1개 추가
.update() # 여러개를 한꺼번에 추가
.remove()

 

기본연산

a= set([1,2,3,4])
b= set([3,4,5,6])
print(a|b) # 합집합
print(a&b) # 교집합
print(a-b) # 차집합

{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}

 

itertools

from itertools import combinations, permutations, product
data =["A","B","C"]
print(list(combinations(data,2)))
print(list(permutations(data,2)))
print(list(product(data,repeat=2)))

[('A', 'B'), ('A', 'C'), ('B', 'C')]
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]

 

sort

s.sort(key = lambda x : (-int(x[1]), int(x[2]))) # 정렬순서 기본은 오름차순

 

N=5
stages = [1,5,3,2,1]
ans = []
length = len(stages)
for i in range(1, N+1):
    count = stages.count(i)
    if length == 0:
        failure_rate = 0
    else:
        failure_rate = count/length
    ans.append((i,failure_rate))
    length -= count
ans= sorted(ans,key = lambda x: x[1],reverse = True)
ans

[(5, 1.0), (3, 0.5), (1, 0.4), (2, 0.3333333333333333), (4, 0.0)]

 

heap 우선순위큐

import heapq
heap =[]
data = list(map(int,input().split()))
for i in range(len(data)):
    heapq.heappush(heap,data[i])
result =0
while len(heap) !=1:
    one = heapq.heappop(heap)  #가장 작은값 추출
    two = heapq.heappop(heap)  #2번째 작은값 추출
    sum_value = one + two
    result += sum_value
    heapq.heappush(heap,sum_value) # 가장작은 2개 합을 넣는다.
print(heap)
print(result)

1 2 3 4 5 6
[21]
51

 

deque

from collections import deque
data = deque([2,3,4])
data.appendleft(1)
data.append(5)
list(data)

[1, 2, 3, 4, 5]

 

이진탐색 start,mid,end or left, mid, right

array = [1,2,4,8,9] # 공유기설치할 집 좌표
N=len(array)
C=3
start = 1
end = array[-1] - array[0]
while start <= end:
    mid = (start+end)//2
    value = array[0]
    count = 1
    for i in range(1,N):
        if array[i] > value+mid:
            value=array[i]
            count +=1
    if count >= C:
        start = mid+1
        result = mid    #인접한 두 공유기 사이 거리 gap
    else:
        end = mid-1
print(result)

2

 

bisect

a = [1,2,5,5,6]   # Test
print(bisect_left(a,2)) # 1
print(bisect_right(a,5)) # 4

1
4

 

from bisect import bisect_left, bisect_right

# 값이 [left_value, right_value]인 데이터의 개수를 반환하는 함수
def count_by_range(a, left_value, right_value):
    right_index = bisect_right(a, right_value)
    left_index = bisect_left(a, left_value)
    return right_index - left_index

a = [1,2,5,5,6]   # Test
print(bisect_left(a,2)) # 출력 1
print(bisect_right(a,5)) # 출력 4

# 모든 단어들을 길이마다 나누어서 저장하기 위한 리스트
array = [[] for _ in range(10001)]
# 모든 단어들을 길이마다 나누어서 뒤집어 저장하기 위한 리스트
reversed_array = [[] for _ in range(10001)]

def solution(words, queries):
    answer = []
    for word in words: # 모든 단어를 접미사 와일드카드 배열, 접두사 와일드카드 배열에 각각 삽입
        array[len(word)].append(word) # 단어를 삽입
        reversed_array[len(word)].append(word[::-1]) # 단어를 뒤집어서 삽입

    for i in range(10001): # 이진 탐색을 수행하기 위해 각 단어 리스트 정렬 수행
        array[i].sort()
        reversed_array[i].sort()

    for q in queries: # 쿼리를 하나씩 확인하며 처리
        if q[0] != '?': # 접미사에 와일드 카드가 붙은 경우
            res = count_by_range(array[len(q)], q.replace('?', 'a'), q.replace('?', 'z'))
        else: # 접두사에 와일드 카드가 붙은 경우
            res = count_by_range(reversed_array[len(q)], q[::-1].replace('?', 'a'), q[::-1].replace('?', 'z'))
        # 검색된 단어의 개수를 저장
        answer.append(res)
    return answer

1
4

 

BFS

from collections import deque

N,M=map(int,input().split())
graph=[]
for i in range(N):
    graph.append(list(map(int,input())))
dx=[-1,1,0,0]
dy=[1,0,1,-1]

def bfs(x,y):
    q=deque()
    q.append((x,y))
    while q:
        x,y, = q.popleft()
        for i in range(4):
            nx = x+dx[i]
            ny = y+dy[i]
            if 0<= nx < N and 0<= ny <M and graph[nx][ny] !=0:
                graph[nx][ny] = graph[x][y] +1
                q.append((nx,ny))
    return graph[N-1][M-1]

print(bfs(0,0))

2 1
5
3
6

 

Flood Fill

from collections import deque

def solution(n, m, image):
    # bfs 풀이 -> 큐를 인덱스에 넣어줘야겠다.
    answer = 0
    visited = [[False for _ in range(m)] for _ in range(n)]
    direction = [(0,1),(1,0),(-1,0),(0,-1)]
    
    for py in range(n):
        for px in range(m):
            if visited[py][px]:
                continue
                
            visited[py][px] = True
            Q = deque([(py,px)])
            cur_area = image[py][px]

            while Q:
                y,x = Q.popleft()
                    
                for d in direction:
                    ny = y + d[0]
                    nx = x + d[1]

                    if (0 <= ny < n and 0 <= nx < m) and not visited[ny][nx] and image[ny][nx] == cur_area:
                        visited[ny][nx] = True
                        Q.append((ny,nx))
            answer += 1
    return answer

n=2
m=3
image =[[1,2,3],[2,1,3]]
solution(n, m, image)

5