전체 글 191

itertools(permutations, combinations, product) 정리

🔷 permutationsitertools.permutations(iterable, r)iterable 중에 r개의 요소를 중복 없이 뽑은 순열 🔷 combinationsitertools.combinations(iterable, r)iterable 중에 r개의 요소를 중복 없이 뽑은 조합 🔷 combinations_with_replacementitertools.combinations_with_replacement(iterable, r)iterable 중에 r개의 요소를 중복 허용하여 뽑은 조합  위 세개 함수 사용 예) 12345678910import itertools nums = [1,2,3] print(list(itertools.permutations(nums, 2)))# [(1, 2), (1,..

백준_python 16953번 A → B (BFS, 그래프 깊이)

링크> https://www.acmicpc.net/problem/16953   🔷 sol) bfs를 이용한 목표 값 탐색, 노드 깊이로 연산 횟수 계산123456789101112131415161718from collections import deque MAX = 10 ** 9 def bfs(n):    q = deque([(n, 1)])     # (노드, 변환 횟수)    while q:        v, cnt = q.popleft()        if v == b:            return cnt        for w in [v * 2, (v * 10) + 1]:            if w = MAX:                # cnt + 1 : 자식 노드는 현재 노드보다 깊이 + ..

백준_python 2468번 안전 영역 (BFS, DFS, 부르트포스 그래프)

링크>https://www.acmicpc.net/problem/2468어떤 지역의 높이 정보가 주어졌을 때, 장마철에 물에 잠기지 않는 안전한 영역의 최대 개수를 계산하는 프로그램을 작성하시오.   🔷 sol 1) DFS_재귀(Recursion)123456789101112131415161718192021222324252627282930313233343536import syssys.setrecursionlimit(10 ** 5)input = sys.stdin.readline # 상하좌우 좌표dx = [-1, 1, 0, 0]dy = [0, 0, -1, 1] def dfs(x, y, h, visited):    visited[x][y] = True     for m in range(4):        nx ..

백준_python 7576번 토마토 (그래프, BFS)

링크>https://www.acmicpc.net/problem/7576  12345678910111213141516171819202122232425262728293031323334353637import sysfrom collections import deque input = sys.stdin.readline def bfs(m, n, ground):    directions = [(-1,0),(1,0),(0,-1),(0,1)]    # 동서남북 방향벡터 정의        # 토마토 위치 = bfs 시작할 위치 저장    q = deque([(i, j) for i in range(m) for j in range(n) if ground[i][j] == 1])        while q:        x, y ..

알고리즘 문제 유형 - 그래프 (DFS, BFS, 백트래킹, 제약충족문제)

🔷 그래프 🔹구성정점(node), 간선(edge) 🔹그래프 종류방향 기준무방향(= 양방향) 그래프방향 그래프순환성 기준 순환 그래프 (cyclic graph) - 한군데라도 cycle이 있으면 순환그래프비순환 그래프(acyclic graph) - cycle이 하나도 없으면 비순환 그래프방향성 비순환 그래프(DAG, Directed Acyclic Graph )연결 요소로 이루어진 그래프도 존재  🔷 그래프 표현 방법1. 인접행렬 (Adjacency Matrix) 간선 정보를 0 또는 1로 해서 [출발노드][도착노드]로가는 간선이 존재하면 1, 존재하지 않으면 0으로 표기 무방향(양방향)그래프의 경우 두 노드 간 간선이 두개라고 볼 수 있으므로인접행렬이 대각선 기준으로 대칭 구조 2. 인접리스트(연결..

백준_python 11659번 구간 합 구하기 4 (누적합, 시간초과)

링크>https://www.acmicpc.net/problem/11659 1234567891011121314151617181920import sysinput = sys.stdin.readdata = input().split()  # 한번에 입력 받기 n, m = map(int, data[0:2]) nums = list(map(int, data[2:n+2])) sums = [0] * (n+1)      # 누적합 저장할 sums 배열 초기화for i in range(1, n+1):    sums[i] = sums[i-1] + nums[i-1] index = n+2results = []for _ in range(m):    a = int(data[index])    b = int(data[index + 1]..

백준_python 9375번 패션왕 신해빈(딕셔너리)

링크>https://www.acmicpc.net/problem/9375   123456789101112131415161718t = int(input()) for _ in range(t):    n = int(input())    clothes = dict()    for _ in range(n):        name, type = map(str, input().split())        if type in clothes.keys():            clothes[type].append(name)        else:            clothes[type] = [name]    cnt = 1     for k in clothes:        cnt *= len(clothes[k]) + 1..

정규표현식_python 단어만 남기고 비단어 문자 제거

🔷 예제 코드 123456789import re paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."banned = ["hit"] words = [word for word in re.sub(r'\W+', ' ', paragraph).lower().split() if word not in banned] print(words)    # ['bob', 'a', 'ball', 'the', 'ball', 'flew', 'far', 'after', 'it', 'was']cs  🔷 re.sub(r'\W+', ' ', paragraph)=> paragraph라는 문자열에서 연속된 모든 비단어 문자를 찾아 이를 단일 공백 문자 ' '로 대체   ..

백준_python 10942번 팰린드롬?(시간초과, DP)

https://www.acmicpc.net/problem/10942 10942번: 팰린드롬? 총 M개의 줄에 걸쳐 홍준이의 질문에 대한 명우의 답을 입력으로 주어진 순서에 따라서 출력한다. 팰린드롬인 경우에는 1, 아닌 경우에는 0을 출력한다. www.acmicpc.net 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import sys input = sys.stdin.readline n = int(input()) list_n = list(map(int, input().split())) m = int(input()) dp_table = [[0] * (n+1) for _ in range(n+1)] for i in range(1,n..

백준_python 1003번 피보나치 함수(다이나믹프로그래밍)

https://www.acmicpc.net/problem/1003 1003번: 피보나치 함수 각 테스트 케이스마다 0이 출력되는 횟수와 1이 출력되는 횟수를 공백으로 구분해서 출력한다. www.acmicpc.net 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def fibonacci(n) : zeros = [1, 0, 1] ones = [0, 1, 1] if n >= 3: for i in range(2,n): zeros.append(zeros[i-1] + zeros[i]) ones.append(ones[i-1] + ones[i]) print(zeros[n], ones[n]) t = int(input()) for _ in range(t): n = int(input()) fibonacci(n)..