본문 바로가기

iterative3

[자료구조] 이진탐색 (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.
[자료구조] 재귀함수 파이썬 (recursive, iterative, decorator, reduce) Fibonacci 피보나치 (recursively & iteratively) 삼항 연산자(Ternary operators)로 풀이 (출처는 아래에) # basic recusrive solution def fibo(n): return fibo(n-1) + fibo(n-2) if n >= 2 else n # basic iterative solution def fibo(n): if n < 2: return n a, b = 0, 1 for i in range(n-1): a, b = b, a + b return b # iterative w/ DP def fibo(n): if n < 2: return n cache = [0 for _ in range(n+1)] cache[1] = 1 for i in range(2,.. 2021. 4. 20.
[LeetCode] Symmetric Tree 파이썬 (iterative, recursion) iterative solution (32ms) class Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): if root is None: return True stack = [] stack.append(root.left) stack.append(root.right) while stack: p, q = stack.pop(), stack.pop() if p is None and q is None: continue if p is None or q is None or p.val != q.val: return False stack.append(p.left) stack.append(q.right) stack.ap.. 2021. 3. 31.