본문 바로가기

DC 228

[자료구조] 사탕 담기 파이썬 파이썬 조합을 활용해서 풀었는데 더 간편하게 푸는 방법이 있을 것 같다. from itertools import combinations def solution(m, weights): cnt = 0 for i in range(1,len(weights)): COMB = combinations(weights,i) for comb in list(COMB): if sum(comb) == m: cnt += 1 return cnt 조합을 구성하는 개수를 1부터 len(weights)까지 모든 조합을 순회하면서 조합내에서 만들어진 list의 원소들(tuple)의 합이 m인지 확인하면서 탐색한다. 효율적인 방법이 있을텐데 2021. 4. 20.
[자료구조] 카펫 파이썬 이 문제는 전에 풀었던 문제다 한참걸려 했지만 못푼 문제 내가 느끼기에 가장 쉽게 푼 방법은 방정식을 활용한 것이다. def solution(brown, red): x = (brown + 4 + ((brown + 4)**2 - 16*(brown+red))**0.5)/4 y = (brown + red) // x return [max(x,y), min(x,y)] ygseo.tistory.com/159 [프로그래머스] 카펫 파이썬 완전탐색으로 푸는 방법 def solution(brown, red): for a in range(1, int(red**0.5)+1): if not red % a: b = red // a if 2*a + 2*b + 4 == brown: return [b+2, a+2] 출처: geonl.. 2021. 4. 20.
[자료구조] 운송 트럭 파이썬 (dict) def solution(max_weight, specs, names): answer = [] answer.append(None) print(answer) specs = dict(specs) # print(specs) tmp = 0 cnt = 1 for n in names: tmp += int(specs[n]) if tmp > max_weight: cnt += 1 tmp = int(specs[n]) # print(tmp, cnt) return cnt 처음에 pseudo 코드로 만들고 풀었을때 에러가 났던 부분은 if 문에서 tmp를 int(specs[n])이 아니라 0로 설정해서 안풀렸다 tmp에 새로운 무게를 추가했을때, max_weight을 초과하게 되면 tmp는 추가한 무게로 초기화 시켜주는 것이 중.. 2021. 4. 20.
[자료구조] 나머지 한 점 파이썬 Counter를 사용해서 풀었는데 더 간편하게 풀 수 있는 방법이 있을 것 같다. from collections import Counter def solution(v): x = [x for x,y in v] y = [y for x,y in v] # print(x,y) xd = Counter(x) yd = Counter(y) answer = [] for k,v in xd.items(): if v == 1: answer.append(k) for k,v in yd.items(): if v == 1: answer.append(k) return answer # return answer 2021. 4. 20.
[자료구조] 스택 파이썬(LeetCode, Programmers) class ArrayStack: def __init__(self): self.data = [] def size(self): return len(self.data) def isEmpty(self): return self.size() == 0 def push(self, item): self.data.append(item) def pop(self): return self.data.pop() def peek(self): return self.data[-1] def solution(expr): match = { ')': '(', '}': '{', ']': '[' } S = ArrayStack() for c in expr: if c in '({[': S.push(c) elif c in match: if S.size.. 2021. 4. 20.
[자료구조] Doubly Linked List 구현 class Node: def __init__(self, item): self.data = item self.prev = None self.next = None class DoublyLinkedList: def __init__(self): self.nodeCount = 0 self.head = Node(None) self.tail = Node(None) self.head.prev = None self.head.next = self.tail self.tail.prev = self.head self.tail.next = None def reverse(self): result = [] curr = self.tail while curr.prev.prev: curr = curr.prev result.append(c.. 2021. 4. 20.
[자료구조] Linked List 클래스 구현 class Node: def __init__(self, item): self.data = item self.next = None class LinkedList: def __init__(self): self.nodeCount = 0 self.head = Node(None) self.tail = None self.head.next = self.tail def traverse(self): result = [] curr = self.head while curr.next: curr = curr.next result.append(curr.data) return result def getAt(self, pos): if pos self.nodeCount: return None i = 0 curr.. 2021. 4. 20.
[자료구조] (singly) Linked List 파이썬 연결리스트를 끝까지 순회하는 방법 LeetCode 같은 경우 # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next def traverse(self): if self.head == None: return [] curr = self.head res = [] while curr: res.append(curr.data) curr = curr.next return res 2021. 4. 20.
[자료구조] 이진탐색 (Binary Search) 파이썬 (bisect, recursion, iteration) 일반적인 풀이방법 def solution(L, x): start, end = 0, len(L)-1 while start = low: mid = (high + low) // 2 # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it can only # be present in left subarray elif arr[mid] > x: return binary_search(arr, low, mid - 1, x) # Else the element can only be present in right subarray else: return binary_search.. 2021. 4. 20.