본문 바로가기

분류 전체보기

(31)
7/20 코테 일지 (Helper 함수) 1. Helper 함수https://leetcode.com/problems/path-sum/description/Class 내 정의된 nested 함수를 helper 함수라고 부른다. 이 helper 함수는 클래스 내에서만 사용되는 보조적인 역할을 하며, 주로 클래스의 메서드들이 수행해야 하는 반복적인 작업을 분리하여 코드의 가독성을 높이고, 중복을 줄이기 위해 사용된다.밑의 코드는 내가 짠 코드이며 helper 함수를 사용하지 않는다.class Solution(object): def hasPathSum(self, root, targetSum,sum =0): if not root: return False sum += root.val if no..
NeetCode 22번 알고리즘 Tree Maze AlgorithmQ: Determine if a path exists from the root of the tree to a leaf node. It may not contain any zeroes. Codeclass TreeNode: def __init__(self, val): self.val = val self.left = None self.right = Nonedef leafPath(root, path): if not root or root.val == 0: return False path.append(root.val) if not root.left and not root.right: return True if..
7/10 코테 일지 (exec() 함수) exec() 함수#1991 트리 순회 트리 순회 문제에서 input이 알파벳으로 들어오면 해당 알파벳을 이름으로 가지는 새로운 TreeNode()를 생성하여야 했다. 어떻게 하면 가능할까 하였는데 exec() 함수를 사용하면 가능하였다. import sysn = int(sys.stdin.readline().rstrip())root_set = set()for _ in range(n): input = sys.stdin.readline().rstrip().split(' ') for node in input : if node not in root_set and node != '.': root_set.add(node) exec(f"{node} = TreeNode('{node}')") ..
자료구조 Set and Map (Hash 기반 vs Tree 기반) (NeetCode 21번 알고리즘 : BST Sets and Maps ) 자료구조 Set 자료구조에서의 set는 단순히 , 고유한 요소들의 모음을 나타내는 class이다.Tree 기반 set와 해시 기반 Set가 존재한다.  특징1. 중복된 요소가 없음.2. 순서가 없음.3. 변경 가능 (추가, 제거 가능) 해시 기반 Set대부분 set는 해시 테이블 기반으로 만들어지며, insert, add 등이 O(1)의 시간 복잡도를 가진다.  Initializethisset = set()# thisset = {}를 하면 dict로 인식하기 때문에 초기화는 set()로 해준다. thisset = {1,2,3}# set 초기화 Add and Removethisset.add(4)thisset.remove(3) Set Operations# 합집합union_set = set1 | set2pri..
7/9 코테 일지 (BFS 응용) 1. BFS 응용 11725 트리의 부모 찾기 처음에는 트리의 특성을 사용하지 않고 단순히 논리적으로 queue를 사용하여 풀었다. import sys from collections import dequen = int(sys.stdin.readline().rstrip())ans = [0 for _ in range(n)]ans[0] = 1 queue = deque()for _ in range(n-1): input = list(map(int,sys.stdin.readline().rstrip().split(' '))) queue.append(input)while queue: input = queue.popleft() if ans[input[0]-1] != 0 : ans[input[1]-1] = i..
NeetCode 20번 알고리즘 : Breadth-First Search Algorithm Codedef bfs(root): queue = deque() if root: queue.append(root) level = 0 while len(queue) > 0: print("level: ", level) for i in range(len(queue)): curr = queue.popleft() print(curr.val) if curr.left: queue.append(curr.left) if curr.right: queue.append(curr.right) level ..
7/8 코테 일지 ((중요!) Immutable Types, Iterative Inorder, pre와 in으로 build tree) 1. Immutable Typeshttps://neetcode.io/problems/kth-smallest-integer-in-bst 여기서 배열은 nested 되어있는 inorder 밖에서 선언되었음에도 함수 내에서 append가 가능하다.class Solution: def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: ans = [] def inorder(root) : if root : inorder(root.left) ans.append(root.val) inorder(root.right) inor..
NeetCode 19번 알고리즘 : Depth-First Search 3 types of Depth-First Search- Inorder- Preorder- Postorder Inorder Traversal Recursivedef inorder(root): if not root: return inorder(root.left) print(root.val) inorder(root.right) Iterativedef inorderTraversal(self, root): curr = root stack = [] ans = [] while (curr or stack) : while curr : stack.append(curr) ..
람다 함수 (lambda function) 람다함수를 통해 이름이 없는 함수를 만들 수 있다.def add(x,y): return x+yprint(add(3,4))다음 과 같은 함수를 이름 짓지 않고 바로 출력 가능하다. print((lambda x,y:x+y)(3,4)) 람다 함수에 이름을 붙여주려면 변수에 저장해서 재사용도 가능하다. add = lambda x,y :x+yprint(add(3,4))print(add(4,5)) 람다 함수의 중요한 특징 중 하나가 리스트에 넣어서 사용 가능하다. lambdas = [lambda x,y:x+y, lambda x,y:x-y]print(lambdas[0](7,3))print(lambdas[1](7,3)) 활용배열 안의 배열에 대해서 각 배열 원소의 두 번째 원소를 기준으로 sorting 하고 싶으면a..
7/7 코테 일지 #1654랜선 자르기처음에는 모든 전선을 모두 사용해야 하는 줄 알고 min(k_array)를 했으나 그럴 필요가 없다는 것을 깨닫고 max(k_array)를 하니 풀렸다.import sysk, n = map(int,sys.stdin.readline().rstrip().split(' '))k_array= []for _ in range(k): k_array.append(int(sys.stdin.readline().rstrip()))l, r = 1, max(k_array)ans = 0while (l= n : l = mid + 1 ans = mid elif sum