본문 바로가기

전체 글269

python iso format to datetime python 쓰다 보면 datetime으로 변경할 일이 많다. 특히 중간에 T 와 Z로 이루어진 처음 보는 포맷이 있는데 이건 iso 포맷이고 그냥 별 의미 없이 구분자 역할을 T와 Z로 하는 것으로 알고 있다. import dateutil.parser date_string = '2022-06-22T01:55:58.585Z' dateutil.parser.isoparse('2008-09-03T20:56:35.450686Z') # RFC 3339 format dateutil.parser.isoparse(date_string) # RFC 3339 format --- 결과 --- datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc()) datetime.. 2022. 6. 24.
[MySQL] 그룹별로 column 데이터 이어 붙이기 (GROUP_CONCAT) https://leetcode.com/problems/group-sold-products-by-the-date/ Group Sold Products By The Date - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 위 문제를 풀면서 알게 된 점 정리 일단 문자열을 붙일 때는 CONCAT, CONCAT_WS 들을 많이 사용함 CONCAT은 문자열 그대로 붙이는 거고 CONCAT_WS는 구분자 두는 것 그룹별로 데이터를 이어 붙일 땐 GROUP_CONCAT을 .. 2022. 5. 4.
[Python] 트라이 자료구조 구현(Trie) 트라이 자료구조는 검색에 최적화된 자료구조이다 자식 노드가 여러 개인 트리 형태로 구성된다고 이해하면 된다. https://leetcode.com/problems/implement-trie-prefix-tree/ Implement Trie (Prefix Tree) - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 위의 문제를 기준으로 구현했다. class TrieNode: def __init__(self): self.word = False self.childre.. 2022. 4. 30.
Python 힙 구현 힙 자료구조를 만족하려면 두 가지 조건(최소 힙 기준) 1. 부모 노드가 자식 노드보다 작다. 2. 트리의 모양이 완전 이진트리의 형태. 완전 이진트리는 마지막 레벨을 제외하고 모든 노드가 왼쪽에서 오른쪽으로 채워져 있는 트리 -> 리스트로 구현 class BinaryHeap: def __init__(self): self.items = [None] def __len__(self): return len(self.items) - 1 # 위로 올라가는거 def _percolate_up(self): index = len(self) parent = index // 2 while parent > 0: if self.items[parent] > self.items[index]: self.items[parent], s.. 2022. 4. 23.
[Python] shorten url (base64, url safe base64) URL에는 많은 정보가 담김. 그러다 보니 URL이 길어지는 문제가 발생 -> 불편하다! -> 이를 줄이기 위해 shorten url에 대한 고민이 생김 어떤 값을 Encode와 Decode를 하는 여러 가지 방법이 있는데, 알파벳과 로마자로 encode 하는 방식을 base62라고 함 1. a-z : 26개 2. A-Z : 26개 3. 0-9 : 10개 총합 : 62 그래서 base62 특수문자 2개 추가하면 base64 근데 여기 추가되는 두 개 특수문자가 + 와 /인데 이는 url에서 특별한 의미를 가지기 때문에 이렇게 쓰면 안 됨. 그래서 각각 - , _ 로 변환해준 게 base64 url-safe 아래 문제를 풀어봐도 좋겠다. https://leetcode.com/problems/encode-a.. 2022. 4. 23.
[Python] 수행시간 f string 코드 수행 시간 체크할 때 import time 해서 사용하는데, 그게 보기 불편하다. python f string 포맷팅을 사용해서 쉽게 보자 import time start = time.time() print(15 % (2 ** 15)) print(f'{time.time()-start:.3f} sec') # 실행결과 : 0.001 sec start = time.time() print(15 % (1 2022. 4. 21.
[LeetCode] Balanced Binary Tree (균형 이진 트리 확인 Python) https://leetcode.com/problems/balanced-binary-tree/ Balanced Binary Tree - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 이진트리가 균형 잡힌 트리인지 확인하는 문제 -> 균형 잡혔단 뜻은 모든 노드의 서브 트리 간의 높이 차이가 1 이하 깔끔한 풀이 class Solution: def isBalanced(self, root): self.bal = True def dfs(node): if not node.. 2022. 4. 20.
[MySQL] SUM + CASE WHEN + GROUP BY 처리 https://leetcode.com/problems/capital-gainloss/ 위 문제를 풀고 내용 정리 주식 별로 얼마나 손익을 봤는지 계산하는 문제 처음엔 GROUP BY stock_name, operation 이렇게 묶고 SELECT 한번 더 해서 나중에 처리하려고 했는데 뭔가 잘 되지 않았다. SUM 안에 CASE WHEN을 넣어서 처리하면 깔끔하게 풀이할 수 있다. # Write your MySQL query statement below SELECT stock_name, SUM( CASE WHEN operation = 'Buy' THEN -price ELSE price END ) AS capital_gain_loss FROM Stocks GROUP BY stock_name ; 2022. 4. 20.
[LeetCode] Trim a Binary Search Tree (트리 순환 재귀) https://leetcode.com/problems/trim-a-binary-search-tree/ Trim a Binary Search Tree - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 재귀로 트리를 선회하는 방식이 이제 이해가 되는 거 같다. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.va.. 2022. 4. 15.
[LeetCode] Spiral Matrix II (나선 매트릭스 순환) https://leetcode.com/problems/spiral-matrix-ii/ Spiral Matrix II - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 나선 방향 매트릭스 순환에 대한 문제다. 아주 참신한 방법으로 풀이한 방법이 있어 남기려 한다. class Solution: def generateMatrix(self, n: int) -> List[List[int]]: matrix = [[0] * n for _ in range(n)] x, y, d.. 2022. 4. 13.
[LeetCode] Game of Life https://leetcode.com/problems/game-of-life/ Game of Life - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 주위 살아있는 세포들의 개수를 세서 살아갈지 죽을지를 결정하는 문제다. 결론은 주위에 세포가 몇 개 살아있는지를 세면 된다. class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """ Do not return anything, modify .. 2022. 4. 12.
[Python] 피보나치 구현 정리 피보나치를 구현하는 방법에 대해 정리 1. 기본 재귀 def fibo(n): if n == 0: return 0 if n == 1: return 1 return fibo(n-1) + fibo(n-2) 2. bottom up 방식 def fibo(n): if n == 0: return 0 if n == 1: return 1 memo = [0] * (n + 1) memo[1] = 1 for i in range(2, n + 1): memo[i] = memo[i - 1] + memo[i - 2] return memo[n] 위 코드는 공간 복잡도가 n이 커짐에 따라 선형적으로 증가하기 때문에 O(n) 3. bottom up 방식 + 공간 복잡도 효율 def fibo(n): if n == 0: return 0 me.. 2022. 4. 10.
[LeetCode] Diameter of Binary Tree (이진트리 가장 긴 경로) https://leetcode.com/problems/diameter-of-binary-tree/ Diameter of Binary Tree - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com class Solution: longest: int = 0 def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: def dfs(node): if not node: return -1 left = dfs(node.l.. 2022. 4. 8.
[LeetCode] Maximum Depth of Binary Tree (이진트리 최대 깊이 구하기) https://leetcode.com/problems/maximum-depth-of-binary-tree/ Maximum Depth of Binary Tree - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 트리에서 깊이(Depth)는 루트에서부터 현재 노드까지의 거리이다. 최대 깊이는 리프 노드까지 거리 중 가장 긴 거리를 구하면 된다. 재귀 방식 # Definition for a binary tree node. # class TreeNode: # def _.. 2022. 4. 8.
[Python] 순열 조합 구현 순열 def permute(self, nums: List[int]) -> List[List[int]]: answer = [] prev_elements = [] def dfs(elements): if len(elements) == 0: answer.append(prev_elements[:]) return for e in elements: next_elements = elements[:] next_elements.remove(e) prev_elements.append(e) dfs(next_elements) prev_elements.pop() dfs(nums) return answer 조합 def combine(self, n: int, k: int) -> List[List[int]]: answer = [] n.. 2022. 4. 8.