본문 바로가기
728x90

Programming/Python46

[프로그래머스] 전화번호 목록 기본 아이디어트라이 노드순서 정렬 or 양방향 접두사 여부 체크class TrieNode: def __init__(self): self.children = {} self.is_end = Falseclass Trie: def __init__(self): self.root = TrieNode() def insert(self, number): node = self.root for n in number: if n not in node.children: node.children[n] = TrieNode() node = node.children[n] node... 2025. 4. 12.
[프로그래머스] 피로도 기본 아이디어가능한 경우의 수가 크지 않아 모든 경우의 수를 구해도되겠다순열이다from itertools import permutationsdef solution(k, dungeons): max_count = 0 for order in permutations(dungeons): count = 0 fatigue = k for required, cost in order: if required > fatigue: break fatigue -= cost count += 1 max_count = max(max_count, count) return max_count.. 2025. 4. 10.
[프로그래머스] 가장 큰 수 기본 아이디어sort문자열로 다 바꾸고 비교해서 합치기from functools import cmp_to_keydef solution(numbers): def compare(x, y): if x + y > y + x: return -1 # x를 y보다 앞에 둔다 elif x + y cmp_to_key는 왜 쓰냐??? -> sort함수는 key만 받음, 비교함수를 직접 받지 않음 -> 이게 비교함수를 key로 바꿔주는 역할을 함마지막에 '000' 이런게 답인 엣지 케이스 고려해줘야함 2025. 4. 10.
[프로그래머스] 올바른 괄호 기본 아이디어스택이게 왜 2단계?from collections import dequedef solution(s): stack = deque([]) for chr in s: if chr == "(": stack.append(chr) elif not stack: return False else: stack.pop() return not stackdeque은 굳이 쓸 필요없음 여기서는 list랑 시간복잡도 동일 -> 다만 스택입니다요!! 하고 직관적이긴 함 deque쓰면pop한게 "("인지 체크할 필요는 없다. 애초에 "("만 스택에 들어간다return not stack으로 마무리하는건 챗지피티.. 2025. 4. 9.
[프로그래머스] 카펫 기본 아이디어사실상 brown의 개수는 yellow에 의존하기 때문에yellow 만 고려해서 코드를 짜면 되곘다그리고 그냥 구현같음def solution(brown, yellow): total = brown + yellow for yr in range(1, int(yellow ** 0.5) + 1): if yellow % yr != 0: continue yc = yellow // yr if total == (yc + 2) * (yr + 2): return [yc + 2, yr + 2]for문 돌 때 range(1, yellow)까지 갈 필요 없고, sqrt(yellow)까지 가면 됨 -> yc > yr이 항상 보장 됨 2025. 4. 9.
[프로그래머스] 기능개발 기본 아이디어현재 날짜에 이미 작업 완료된 프로세스들을 cnt할 방법 -> 아무래도 while문코드import mathfrom collections import dequedef solution(progresses, speeds): answer = [] days = deque([math.ceil((100 - p) / s) for p, s in zip(progresses, speeds)]) while days: cur = days.popleft() cnt = 1 while days and days[0] 처음부터 모든 태스크에 필요한 작업일수를 미리 계산해놓고 들어가는 방법 2025. 4. 8.
728x90