본문 바로가기

reduce3

[자료구조] 재귀함수 파이썬 (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.
[Bit Operation] 비트연산 NOT 연산은 각 자릿수의 값을 반대로 바꾸는 연산이다. NOT 0111 = 1000 OR 연산은 두 값의 각 자릿수를 비교해, 둘 중 하나라도 1이 있다면 1을, 아니면 0을 계산한다. 0101 OR 0011 = 0111 XOR 연산은 두 값의 각 자릿수를 비교해, 값이 같으면 0, 다르면 1을 계산한다. 0101 XOR 0011 = 0110 AND 연산은 두 값의 각 자릿수를 비교해, 두 값 모두에 1이 있을 때에만 1을, 나머지 경우에는 0을 계산한다. 0101 AND 0011 = 0001 XOR 연산을 많이 봤는데 XOR 연산이 0으로만 된 bit를 return 한다면 같은 숫자(?)라는 것을 의미하고 아니라면 다르다는 것을 알 수 있다. [LeetCode] Find the Difference 문.. 2021. 4. 14.
[LeetCode] Find the Difference 파이썬 (Counter, A.subtract(B), bit operation, xor, reduce) from collections import Counter class Solution: def findTheDifference(self, s: str, t: str) -> str: if len(s) == 0: return t # s = "" S = Counter(s) T = Counter(t) T.subtract(S) # inplace res = [k for k, v in T.items() if v > 0] return res[0] Counter 클래스에는 subtract라는 메서드가 있다. inplace이기 때문에 이 점을 유의할 것. 다른 풀이들 class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str.. 2021. 4. 14.