Skip to content

Commit 8090be8

Browse files
author
aaron.liu
committed
new commits
1 parent a2fce71 commit 8090be8

8 files changed

+272
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import collections
2+
3+
class MovingAverage:
4+
5+
def __init__(self, size: int):
6+
self.queue = collections.queue()
7+
self.size = size
8+
self.total = 0
9+
10+
11+
def next(self, val: int) -> float:
12+
13+
if len(self.queue) < self.size:
14+
self.queue.append(val)
15+
self.total += val
16+
return self.total / len(self.queue)
17+
else:
18+
removal = self.queue.popleft()
19+
self.queue.append(val)
20+
self.total = self.total - removal + val
21+
return self.total / self.size
22+
23+
# Your MovingAverage object will be instantiated and called as such:
24+
# obj = MovingAverage(size)
25+
# param_1 = obj.next(val)
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import collections
2+
3+
class Solution:
4+
# 先计算s的counter, 然后按照order的顺序逐个append to res, 最后加上剩余counter里面的
5+
def customSortString(self, order: str, s: str) -> str:
6+
if not order or not s: return ""
7+
8+
9+
res = ""
10+
for char in order:
11+
if char in counter:
12+
while counter[char] > 0: # 必须要把counter里的所有都取出append. eg. s='eqe' order='eq',output='eeq'
13+
counter[char] -= 1
14+
res += char
15+
for c, freq in counter.items():
16+
while counter[c] > 0: #此部分相同 也可以放入common method
17+
res += c
18+
counter[c] -= 1
19+
return res
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from typing import Optional, List
2+
3+
# Definition for a Node.
4+
class Node:
5+
def __init__(self, val, left=None, right=None):
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
class Solution:
11+
# method 1: DFS in-order traverse a tree, get a node list.
12+
# then link each node, and link head and tail. ->need extra space O(n)
13+
def treeToDoublyList(self, root: 'Optional[Node]') -> 'Optional[Node]':
14+
if not root: return None
15+
16+
head, prev = [None], [None]
17+
self.dfs(root, head, prev)
18+
prev[0].right = head[0]
19+
head[0].left = prev[0]
20+
return head[0]
21+
22+
def dfs(self, node: Node, head: List[Node], prev: List[Node]):
23+
if not node: return
24+
25+
self.dfs(node.left, head, prev)
26+
27+
if prev[0]: # 存在之前的结点(值比当前结点小的结点) 连接node和prev[0]
28+
prev[0].right = node
29+
node.left = prev[0]
30+
else: # 之前结点不存在: 当前结点为值最小的点 记为head
31+
head[0] = node
32+
prev[0] = node # prev[0]往前移动一个 作为下一个节点的左边节点
33+
34+
self.dfs(node.right, head, prev)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from typing import Optional
2+
3+
# Definition for a Node.
4+
class Node:
5+
def __init__(self, val=None, next=None):
6+
self.val = val
7+
self.next = next
8+
9+
class Solution:
10+
# 三种情况:
11+
# 1. no head
12+
# 2. insertVal >= max or inserVal <= min: 插入max->insertVal->min
13+
# 3. 都不是 就直接插入
14+
def insert(self, head: 'Optional[Node]', insertVal: int) -> 'Node':
15+
cur_node = Node(insertVal)
16+
if not head:
17+
cur_node.next = cur_node
18+
return cur_node
19+
20+
dummy = Node(-1)
21+
dummy.next = head
22+
23+
# find min and max value nodes
24+
while head.next != dummy.next and head.val <= head.next.val:
25+
head = head.next
26+
min = head.next # head stops at max
27+
28+
if head.val <= insertVal or insertVal <= min.val:
29+
cur_node.next = min
30+
head.next = cur_node
31+
else:
32+
while head.next.val < insertVal:
33+
head = head.next
34+
cur_node.next = head.next
35+
head.next = cur_node
36+
return dummy.next
37+
38+

ML/attention/single_head_attention.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'''
2+
3+
single head attention.
4+
5+
input: query and key-value
6+
7+
注意力机制首先计算query与每个key的关联性(compatibility),每个关联性作为每个value的weight,各个weight与value相乘后相加,得到输出.
8+
9+
Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) * V
10+
'''
11+
12+
import torch
13+
from torch import nn
14+
15+
class ScaledDotProductAttention(nn.Module):
16+
""" Scaled Dot-Product Attention """
17+
18+
def __init__(self, scale):
19+
super().__init__()
20+
21+
self.scale = scale
22+
self.softmax = nn.Softmax(dim=2)
23+
24+
def forward(self, q, k, v, mask=None):
25+
u = torch.bmm(q, k.transpose(1, 2)) # 1.Matmul
26+
u = u / self.scale # 2.Scale
27+
28+
if mask is not None:
29+
u = u.masked_fill(mask, -np.inf) # 3.Mask
30+
31+
attn = self.softmax(u) # 4.Softmax
32+
output = torch.bmm(attn, v) # 5.Output
33+
34+
return attn, output
35+
36+
37+
if __name__ == "__main__":
38+
n_q, n_k, n_v = 2, 4, 4
39+
d_q, d_k, d_v = 128, 128, 64
40+
41+
q = torch.randn(batch, n_q, d_q)
42+
k = torch.randn(batch, n_k, d_k)
43+
v = torch.randn(batch, n_v, d_v)
44+
mask = torch.zeros(batch, n_q, n_k).bool()
45+
46+
attention = ScaledDotProductAttention(scale=np.power(d_k, 0.5))
47+
attn, output = attention(q, k, v, mask=mask)
48+
49+
print(attn)
50+
print(output)

Stack/LC71SimplifyPath.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
2+
class Solution:
3+
# 先split成list. 用stack
4+
# 如果遇到“..”:
5+
# 如果有stack就pop. 如果“.” or "", continue. else stack.append
6+
def simplifyPath(self, path: str) -> str:
7+
stack = []
8+
pathList = path.split("/")
9+
10+
for string in pathList:
11+
if string == "." or string == "":
12+
continue
13+
elif string == "..":
14+
if stack:
15+
stack.pop() # ..意思是退到上一层
16+
else:
17+
stack.append(string)
18+
19+
return "/" + "/".join(stack)

Tree/LC938RangeSumOfBST.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from typing import Optional
2+
3+
# Definition for a binary tree node.
4+
class TreeNode:
5+
def __init__(self, val=0, left=None, right=None):
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
class Solution:
11+
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
12+
13+
if not root: return 0
14+
15+
if root.val < low: # 当前root小了 在范围外 应该往右走
16+
return self.rangeSumBST(root.right, low, high)
17+
if root.val > high: # 当前root大了 在范围外 应该往左走
18+
return self.rangeSumBST(root.left, low, high)
19+
# 当前root值在给定范围内 可以放到和里 然后递归求左边和右边
20+
return root.val + self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high)

Tree/doordash_num_of_menu_updates.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# https://leetcode.com/discuss/interview-question/1528907/doordash-phone-creen
2+
# reference:
3+
# https://vivo.pub/calculate-tree-node-changes/
4+
5+
from typing import List
6+
7+
8+
class Node:
9+
def __init__(self, key:str=None, val:int=None, children:List['Node']=[]):
10+
self.key = key
11+
self.val = val
12+
self.children = children
13+
14+
def compare_old_and_updated_menus(root_o: Node, root_u: Node) -> int:
15+
return dfs_compare(root_o, root_u)
16+
17+
def count_nodes(root: Node) -> int:
18+
if not root:
19+
return 0
20+
num = 1
21+
for child in root.children:
22+
num += count_nodes(child)
23+
return num
24+
25+
def dfs_compare(root_o: Node, root_u: Node) -> int:
26+
if not root_o and not root_u:
27+
return 0
28+
if not root_o:
29+
return count_nodes(root_u)
30+
if not root_u:
31+
return count_nodes(root_o)
32+
if root_o.key != root_u.key:
33+
return count_nodes(root_u) + count_nodes(root_o)
34+
35+
diff_cnt = 0
36+
if root_o.val != root_u.val:
37+
diff_cnt += 1
38+
39+
origin_map = {}
40+
visited = set()
41+
for child in root_o.children:
42+
origin_map[child.key] = child
43+
44+
for child in root_u.children:
45+
if child.key in origin_map:
46+
visited.add(child.key)
47+
diff_cnt += dfs_compare(origin_map[child.key], child)
48+
else:
49+
diff_cnt += count_nodes(child)
50+
51+
for child in root_o.children:
52+
if child.key not in visited:
53+
diff_cnt += count_nodes(child)
54+
return diff_cnt
55+
56+
57+
# case 1
58+
d_o, e_o, f_o = Node("d", 4), Node("e", 5), Node("f", 6)
59+
b_o, c_o = Node("b", 2, [d_o, e_o]), Node("c", 3, [f_o])
60+
a_o = Node("a", 1, [b_o, c_o]) # a_o is the root_o
61+
62+
f_u = Node("f", 66)
63+
c_u = Node("c", 3, [f_u])
64+
a_u = Node("a", 1, [c_u]) # a_u is the root_u
65+
66+
67+
print(compare_old_and_updated_menus(a_o, a_u))

0 commit comments

Comments
 (0)