upd
BIN
algorithms/labs/lab6/assets/1.png
Normal file
|
After Width: | Height: | Size: 36 KiB |
BIN
algorithms/labs/lab6/assets/2.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
BIN
algorithms/labs/lab6/assets/3.png
Normal file
|
After Width: | Height: | Size: 34 KiB |
29
algorithms/labs/lab6/code/1.py
Normal file
@@ -0,0 +1,29 @@
|
||||
def thief_knapsack(weights, values, M, K):
|
||||
cap = M * K
|
||||
n = len(weights)
|
||||
dp = [0] * (cap + 1)
|
||||
take = [[False] * (cap + 1) for _ in range(n)]
|
||||
for i in range(n):
|
||||
w = weights[i]
|
||||
v = values[i]
|
||||
for c in range(cap, w - 1, -1):
|
||||
if dp[c - w] + v > dp[c]:
|
||||
dp[c] = dp[c - w] + v
|
||||
take[i][c] = True
|
||||
c = cap
|
||||
items = []
|
||||
for i in range(n - 1, -1, -1):
|
||||
if take[i][c]:
|
||||
items.append(i)
|
||||
c -= weights[i]
|
||||
items.reverse()
|
||||
return dp[cap], items
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
weights = [2, 3, 4, 5, 9, 7, 3]
|
||||
values = [3, 4, 5, 8, 10, 7, 6]
|
||||
M = 2
|
||||
K = 10
|
||||
best, items = thief_knapsack(weights, values, M, K)
|
||||
print(best, items)
|
||||
35
algorithms/labs/lab6/code/2.py
Normal file
@@ -0,0 +1,35 @@
|
||||
def matrix_chain_order(p):
|
||||
n = len(p) - 1
|
||||
m = [[0] * n for _ in range(n)]
|
||||
s = [[0] * n for _ in range(n)]
|
||||
for L in range(2, n + 1):
|
||||
for i in range(n - L + 1):
|
||||
j = i + L - 1
|
||||
m[i][j] = 10**18
|
||||
for k in range(i, j):
|
||||
q = m[i][k] + m[k + 1][j] + p[i] * p[k + 1] * p[j + 1]
|
||||
if q < m[i][j]:
|
||||
m[i][j] = q
|
||||
s[i][j] = k
|
||||
return m, s
|
||||
|
||||
|
||||
def build_parenthesization(s, i, j, names):
|
||||
if i == j:
|
||||
return names[i]
|
||||
k = s[i][j]
|
||||
return (
|
||||
"("
|
||||
+ build_parenthesization(s, i, k, names)
|
||||
+ build_parenthesization(s, k + 1, j, names)
|
||||
+ ")"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
p = [30, 35, 15, 5, 10, 20, 25]
|
||||
names = ["A", "B", "C", "D", "E", "F"][: len(p) - 1]
|
||||
m, s = matrix_chain_order(p)
|
||||
expr = build_parenthesization(s, 0, len(p) - 2, names)
|
||||
print(m[0][len(p) - 2])
|
||||
print(expr)
|
||||
29
algorithms/labs/lab6/code/3.py
Normal file
@@ -0,0 +1,29 @@
|
||||
def longest_increasing_run(a):
|
||||
if not a:
|
||||
return 0, -1, -1
|
||||
best_len = 1
|
||||
best_l = 0
|
||||
best_r = 0
|
||||
cur_len = 1
|
||||
cur_l = 0
|
||||
for i in range(1, len(a)):
|
||||
if a[i] > a[i - 1]:
|
||||
cur_len += 1
|
||||
else:
|
||||
if cur_len > best_len:
|
||||
best_len = cur_len
|
||||
best_l = cur_l
|
||||
best_r = i - 1
|
||||
cur_len = 1
|
||||
cur_l = i
|
||||
if cur_len > best_len:
|
||||
best_len = cur_len
|
||||
best_l = cur_l
|
||||
best_r = len(a) - 1
|
||||
return best_len, best_l, best_r
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
a = [1, 2, 3, -1, 0, 1, 1, 2, 3, 4, -5]
|
||||
length, l, r = longest_increasing_run(a)
|
||||
print(length, l, r)
|
||||
BIN
algorithms/labs/lab6/in/task.pdf
Normal file
BIN
algorithms/labs/lab6/in/theory.pdf
Normal file
1
algorithms/labs/lab6/leetcode/1/link.txt
Normal file
@@ -0,0 +1 @@
|
||||
https://leetcode.com/problems/regular-expression-matching/submissions/1769086671/?envType=problem-list-v2&envId=dynamic-programming
|
||||
14
algorithms/labs/lab6/leetcode/1/solution.py
Normal file
@@ -0,0 +1,14 @@
|
||||
class Solution:
|
||||
def isMatch(self, s: str, p: str) -> bool:
|
||||
from functools import lru_cache
|
||||
|
||||
@lru_cache(None)
|
||||
def dp(i: int, j: int) -> bool:
|
||||
if j == len(p):
|
||||
return i == len(s)
|
||||
first = i < len(s) and (p[j] == s[i] or p[j] == ".")
|
||||
if j + 1 < len(p) and p[j + 1] == "*":
|
||||
return dp(i, j + 2) or (first and dp(i + 1, j))
|
||||
return first and dp(i + 1, j + 1)
|
||||
|
||||
return dp(0, 0)
|
||||
1
algorithms/labs/lab6/leetcode/2/link.txt
Normal file
@@ -0,0 +1 @@
|
||||
https://leetcode.com/problems/longest-valid-parentheses/submissions/1769090768/?envType=problem-list-v2&envId=dynamic-programming
|
||||
15
algorithms/labs/lab6/leetcode/2/solution.py
Normal file
@@ -0,0 +1,15 @@
|
||||
class Solution:
|
||||
def longestValidParentheses(self, s: str) -> int:
|
||||
n = len(s)
|
||||
dp = [0] * n
|
||||
best = 0
|
||||
for i in range(1, n):
|
||||
if s[i] == ")":
|
||||
if s[i - 1] == "(":
|
||||
dp[i] = (dp[i - 2] if i >= 2 else 0) + 2
|
||||
elif i - dp[i - 1] - 1 >= 0 and s[i - dp[i - 1] - 1] == "(":
|
||||
dp[i] = dp[i - 1] + 2
|
||||
if i - dp[i - 1] - 2 >= 0:
|
||||
dp[i] += dp[i - dp[i - 1] - 2]
|
||||
best = max(best, dp[i])
|
||||
return best
|
||||
1
algorithms/labs/lab6/leetcode/3/link.txt
Normal file
@@ -0,0 +1 @@
|
||||
https://leetcode.com/problems/trapping-rain-water/?envType=problem-list-v2&envId=dynamic-programming
|
||||
20
algorithms/labs/lab6/leetcode/3/solution.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from typing import List
|
||||
|
||||
|
||||
class Solution:
|
||||
def trap(self, height: List[int]) -> int:
|
||||
n = len(height)
|
||||
if n == 0:
|
||||
return 0
|
||||
left = [0] * n
|
||||
right = [0] * n
|
||||
left[0] = height[0]
|
||||
for i in range(1, n):
|
||||
left[i] = max(left[i - 1], height[i])
|
||||
right[-1] = height[-1]
|
||||
for i in range(n - 2, -1, -1):
|
||||
right[i] = max(right[i + 1], height[i])
|
||||
ans = 0
|
||||
for i in range(n):
|
||||
ans += min(left[i], right[i]) - height[i]
|
||||
return ans
|
||||
BIN
algorithms/labs/lab6/out/report.docx
Normal file
BIN
algorithms/labs/lab6/out/report.pdf
Normal file
BIN
algorithms/labs/lab7/assets/1.png
Normal file
|
After Width: | Height: | Size: 35 KiB |
BIN
algorithms/labs/lab7/assets/2.png
Normal file
|
After Width: | Height: | Size: 46 KiB |
BIN
algorithms/labs/lab7/assets/3.png
Normal file
|
After Width: | Height: | Size: 72 KiB |
14
algorithms/labs/lab7/code/1.py
Normal file
@@ -0,0 +1,14 @@
|
||||
def greedy_change(n, coins):
|
||||
result = []
|
||||
for value, count in sorted(coins, key=lambda x: -x[0]):
|
||||
while count > 0 and n >= value:
|
||||
n -= value
|
||||
count -= 1
|
||||
result.append(value)
|
||||
return result if n == 0 else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
coins = [(10, 3), (5, 2), (2, 5), (1, 10)]
|
||||
N = 28
|
||||
print(greedy_change(N, coins))
|
||||
20
algorithms/labs/lab7/code/2.py
Normal file
@@ -0,0 +1,20 @@
|
||||
def greedy_thief(weights, values, M, K):
|
||||
items = list(zip(weights, values))
|
||||
items.sort(key=lambda x: x[1] / x[0], reverse=True)
|
||||
cap = M * K
|
||||
total_value = 0
|
||||
chosen = []
|
||||
for w, v in items:
|
||||
if w <= cap:
|
||||
chosen.append((w, v))
|
||||
cap -= w
|
||||
total_value += v
|
||||
return total_value, chosen
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
weights = [2, 3, 4, 5, 9, 7, 3]
|
||||
values = [3, 4, 5, 8, 10, 7, 6]
|
||||
M = 2
|
||||
K = 10
|
||||
print(greedy_thief(weights, values, M, K))
|
||||
26
algorithms/labs/lab7/code/3.py
Normal file
@@ -0,0 +1,26 @@
|
||||
import heapq
|
||||
|
||||
|
||||
def dijkstra(graph, start):
|
||||
dist = {v: float("inf") for v in graph}
|
||||
dist[start] = 0
|
||||
pq = [(0, start)]
|
||||
while pq:
|
||||
d, v = heapq.heappop(pq)
|
||||
if d > dist[v]:
|
||||
continue
|
||||
for u, w in graph[v]:
|
||||
if dist[v] + w < dist[u]:
|
||||
dist[u] = dist[v] + w
|
||||
heapq.heappush(pq, (dist[u], u))
|
||||
return dist
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
graph = {
|
||||
"Невский": [("Лиговский", 5), ("Гороховая", 3)],
|
||||
"Лиговский": [("Московский", 7)],
|
||||
"Гороховая": [("Московский", 4)],
|
||||
"Московский": [],
|
||||
}
|
||||
print(dijkstra(graph, "Невский"))
|
||||
BIN
algorithms/labs/lab7/in/task.pdf
Normal file
BIN
algorithms/labs/lab7/in/theory.pdf
Normal file
1
algorithms/labs/lab7/leetcode/1/link.txt
Normal file
@@ -0,0 +1 @@
|
||||
https://leetcode.com/problems/wildcard-matching/?envType=problem-list-v2&envId=greedy
|
||||
26
algorithms/labs/lab7/leetcode/1/solution.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from typing import List
|
||||
|
||||
|
||||
class Solution:
|
||||
def isMatch(self, s: str, p: str) -> bool:
|
||||
i = j = 0
|
||||
star = -1
|
||||
match = 0
|
||||
n, m = len(s), len(p)
|
||||
while i < n:
|
||||
if j < m and (p[j] == s[i] or p[j] == "?"):
|
||||
i += 1
|
||||
j += 1
|
||||
elif j < m and p[j] == "*":
|
||||
star = j
|
||||
match = i
|
||||
j += 1
|
||||
elif star != -1:
|
||||
j = star + 1
|
||||
match += 1
|
||||
i = match
|
||||
else:
|
||||
return False
|
||||
while j < m and p[j] == "*":
|
||||
j += 1
|
||||
return j == m
|
||||
1
algorithms/labs/lab7/leetcode/2/link.txt
Normal file
@@ -0,0 +1 @@
|
||||
https://leetcode.com/problems/candy/description/?envType=problem-list-v2&envId=greedy
|
||||
14
algorithms/labs/lab7/leetcode/2/solution.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from typing import List
|
||||
|
||||
|
||||
class Solution:
|
||||
def candy(self, ratings: List[int]) -> int:
|
||||
n = len(ratings)
|
||||
candies = [1] * n
|
||||
for i in range(1, n):
|
||||
if ratings[i] > ratings[i - 1]:
|
||||
candies[i] = candies[i - 1] + 1
|
||||
for i in range(n - 2, -1, -1):
|
||||
if ratings[i] > ratings[i + 1]:
|
||||
candies[i] = max(candies[i], candies[i + 1] + 1)
|
||||
return sum(candies)
|
||||
1
algorithms/labs/lab7/leetcode/3/link.txt
Normal file
@@ -0,0 +1 @@
|
||||
https://leetcode.com/problems/create-maximum-number/?envType=problem-list-v2&envId=greedy
|
||||
46
algorithms/labs/lab7/leetcode/3/solution.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from typing import List
|
||||
|
||||
|
||||
class Solution:
|
||||
def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:
|
||||
def pick(arr: List[int], t: int) -> List[int]:
|
||||
drop = len(arr) - t
|
||||
st = []
|
||||
for x in arr:
|
||||
while drop and st and st[-1] < x:
|
||||
st.pop()
|
||||
drop -= 1
|
||||
st.append(x)
|
||||
return st[:t]
|
||||
|
||||
def greater(a: List[int], i: int, b: List[int], j: int) -> bool:
|
||||
while i < len(a) and j < len(b) and a[i] == b[j]:
|
||||
i += 1
|
||||
j += 1
|
||||
if j == len(b):
|
||||
return True
|
||||
if i < len(a) and a[i] > b[j]:
|
||||
return True
|
||||
return False
|
||||
|
||||
def merge(a: List[int], b: List[int]) -> List[int]:
|
||||
i = j = 0
|
||||
res = []
|
||||
while i < len(a) or j < len(b):
|
||||
if greater(a, i, b, j):
|
||||
res.append(a[i])
|
||||
i += 1
|
||||
else:
|
||||
res.append(b[j])
|
||||
j += 1
|
||||
return res
|
||||
|
||||
m, n = len(nums1), len(nums2)
|
||||
ans = []
|
||||
for i in range(max(0, k - n), min(k, m) + 1):
|
||||
a = pick(nums1, i)
|
||||
b = pick(nums2, k - i)
|
||||
cand = merge(a, b)
|
||||
if not ans or cand > ans:
|
||||
ans = cand
|
||||
return ans
|
||||
BIN
algorithms/labs/lab7/out/report.docx
Normal file
BIN
algorithms/labs/lab7/out/report.pdf
Normal file
BIN
algorithms/labs/lab8/assets/comp/1.png
Normal file
|
After Width: | Height: | Size: 54 KiB |
BIN
algorithms/labs/lab8/assets/comp/2.png
Normal file
|
After Width: | Height: | Size: 41 KiB |
BIN
algorithms/labs/lab8/assets/comp/3.png
Normal file
|
After Width: | Height: | Size: 54 KiB |
BIN
algorithms/labs/lab8/assets/dp/1.png
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
algorithms/labs/lab8/assets/dp/2.png
Normal file
|
After Width: | Height: | Size: 46 KiB |
BIN
algorithms/labs/lab8/assets/dp/3.png
Normal file
|
After Width: | Height: | Size: 39 KiB |
BIN
algorithms/labs/lab8/assets/greedy/1.png
Normal file
|
After Width: | Height: | Size: 50 KiB |
BIN
algorithms/labs/lab8/assets/greedy/2.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
BIN
algorithms/labs/lab8/assets/greedy/3.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
algorithms/labs/lab8/assets/hash/1.png
Normal file
|
After Width: | Height: | Size: 58 KiB |
BIN
algorithms/labs/lab8/assets/hash/2.png
Normal file
|
After Width: | Height: | Size: 58 KiB |
BIN
algorithms/labs/lab8/assets/hash/3.png
Normal file
|
After Width: | Height: | Size: 50 KiB |
BIN
algorithms/labs/lab8/assets/search/1.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
algorithms/labs/lab8/assets/search/2.png
Normal file
|
After Width: | Height: | Size: 42 KiB |
BIN
algorithms/labs/lab8/assets/search/3.png
Normal file
|
After Width: | Height: | Size: 46 KiB |
BIN
algorithms/labs/lab8/assets/sorting/1.png
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
algorithms/labs/lab8/assets/sorting/2.png
Normal file
|
After Width: | Height: | Size: 39 KiB |
BIN
algorithms/labs/lab8/assets/sorting/3.png
Normal file
|
After Width: | Height: | Size: 34 KiB |
15
algorithms/labs/lab8/code/comp/1.py
Normal file
@@ -0,0 +1,15 @@
|
||||
def choose_search_strategy(n, q):
|
||||
cost_linear = q * n
|
||||
cost_binary = n * (n.bit_length()) + q * (n.bit_length())
|
||||
cost_hash = n + q
|
||||
if cost_linear <= cost_binary and cost_linear <= cost_hash:
|
||||
return "linear"
|
||||
if cost_binary <= cost_hash:
|
||||
return "binary_search_with_sort"
|
||||
return "hash_table"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(choose_search_strategy(10**3, 1))
|
||||
print(choose_search_strategy(10**5, 100))
|
||||
print(choose_search_strategy(10**6, 10**6))
|
||||
61
algorithms/labs/lab8/code/comp/2.py
Normal file
@@ -0,0 +1,61 @@
|
||||
def longest_common_len_naive(strs, k):
|
||||
s0 = strs[0]
|
||||
best = 0
|
||||
for i in range(len(s0)):
|
||||
for j in range(i + 1, len(s0) + 1):
|
||||
sub = s0[i:j]
|
||||
cnt = 0
|
||||
for s in strs:
|
||||
if sub in s:
|
||||
cnt += 1
|
||||
if cnt >= k and j - i > best:
|
||||
best = j - i
|
||||
return best
|
||||
|
||||
|
||||
def longest_common_len_optimized(strs, k):
|
||||
import sys
|
||||
|
||||
def has_len(L):
|
||||
if L == 0:
|
||||
return True
|
||||
base = 911382323
|
||||
mod = 10**9 + 7
|
||||
powL = pow(base, L - 1, mod)
|
||||
commons = None
|
||||
for s in strs:
|
||||
if L > len(s):
|
||||
return False
|
||||
h = 0
|
||||
st = set()
|
||||
for t in range(L):
|
||||
h = (h * base + ord(s[t])) % mod
|
||||
st.add(h)
|
||||
for t in range(L, len(s)):
|
||||
h = (h - ord(s[t - L]) * powL) % mod
|
||||
h = (h * base + ord(s[t])) % mod
|
||||
st.add(h)
|
||||
if commons is None:
|
||||
commons = st
|
||||
else:
|
||||
commons &= st
|
||||
if not commons:
|
||||
return False
|
||||
return len(commons) >= k
|
||||
|
||||
lo, hi = 0, min(len(s) for s in strs)
|
||||
ans = 0
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) // 2
|
||||
if has_len(mid):
|
||||
ans = mid
|
||||
lo = mid + 1
|
||||
else:
|
||||
hi = mid - 1
|
||||
return ans
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
strs = ["abracadabra", "cadabracad", "dabrac"]
|
||||
print(longest_common_len_naive(strs, 2))
|
||||
print(longest_common_len_optimized(strs, 2))
|
||||
12
algorithms/labs/lab8/code/comp/3.py
Normal file
@@ -0,0 +1,12 @@
|
||||
def choose_mm_algorithm(n):
|
||||
if n <= 64:
|
||||
return "classical"
|
||||
if n <= 512:
|
||||
return "blocked"
|
||||
return "strassen"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(choose_mm_algorithm(64))
|
||||
print(choose_mm_algorithm(256))
|
||||
print(choose_mm_algorithm(1500))
|
||||
14
algorithms/labs/lab8/code/dp/1.py
Normal file
@@ -0,0 +1,14 @@
|
||||
def word_break(s, wordDict):
|
||||
dp = [True] + [False] * len(s)
|
||||
for i in range(1, len(s) + 1):
|
||||
for w in wordDict:
|
||||
j = i - len(w)
|
||||
if j >= 0 and dp[j] and s[j:i] == w:
|
||||
dp[i] = True
|
||||
break
|
||||
return dp[-1]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(word_break("applepenapple", ["apple", "pen"]))
|
||||
print(word_break("catsandog", ["cats", "dog", "sand", "and", "cat"]))
|
||||
18
algorithms/labs/lab8/code/dp/2.py
Normal file
@@ -0,0 +1,18 @@
|
||||
def min_cost_to_win(n):
|
||||
dp = [[0] * (n + 2) for _ in range(n + 2)]
|
||||
for length in range(2, n + 1):
|
||||
for i in range(1, n - length + 2):
|
||||
j = i + length - 1
|
||||
best = 10**9
|
||||
for p in range(i, j + 1):
|
||||
left = dp[i][p - 1] if p > i else 0
|
||||
right = dp[p + 1][j] if p < j else 0
|
||||
best = min(best, p + max(left, right))
|
||||
dp[i][j] = best
|
||||
return dp[1][n]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(min_cost_to_win(1))
|
||||
print(min_cost_to_win(2))
|
||||
print(min_cost_to_win(10))
|
||||
14
algorithms/labs/lab8/code/dp/3.py
Normal file
@@ -0,0 +1,14 @@
|
||||
def find_max_form(strs, m, n):
|
||||
dp = [[0] * (n + 1) for _ in range(m + 1)]
|
||||
for s in strs:
|
||||
z = s.count("0")
|
||||
o = len(s) - z
|
||||
for i in range(m, z - 1, -1):
|
||||
for j in range(n, o - 1, -1):
|
||||
dp[i][j] = max(dp[i][j], dp[i - z][j - o] + 1)
|
||||
return dp[m][n]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(find_max_form(["10", "0001", "111001", "1", "0"], 5, 3))
|
||||
print(find_max_form(["10", "0", "1"], 1, 1))
|
||||
12
algorithms/labs/lab8/code/greedy/1.py
Normal file
@@ -0,0 +1,12 @@
|
||||
def max_profit(prices):
|
||||
profit = 0
|
||||
for i in range(1, len(prices)):
|
||||
if prices[i] > prices[i - 1]:
|
||||
profit += prices[i] - prices[i - 1]
|
||||
return profit
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(max_profit([7, 1, 5, 3, 6, 4]))
|
||||
print(max_profit([1, 2, 3, 4, 5]))
|
||||
print(max_profit([7, 6, 4, 3, 1]))
|
||||
16
algorithms/labs/lab8/code/greedy/2.py
Normal file
@@ -0,0 +1,16 @@
|
||||
def can_complete_circuit(gas, cost):
|
||||
if sum(gas) < sum(cost):
|
||||
return -1
|
||||
start = 0
|
||||
bal = 0
|
||||
for i in range(len(gas)):
|
||||
bal += gas[i] - cost[i]
|
||||
if bal < 0:
|
||||
start = i + 1
|
||||
bal = 0
|
||||
return start
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(can_complete_circuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]))
|
||||
print(can_complete_circuit([2, 3, 4], [3, 4, 3]))
|
||||
22
algorithms/labs/lab8/code/greedy/3.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from functools import cmp_to_key
|
||||
|
||||
|
||||
def largest_number(nums):
|
||||
arr = list(map(str, nums))
|
||||
|
||||
def cmp(a, b):
|
||||
if a + b < b + a:
|
||||
return 1
|
||||
if a + b > b + a:
|
||||
return -1
|
||||
return 0
|
||||
|
||||
arr.sort(key=cmp_to_key(cmp))
|
||||
res = "".join(arr)
|
||||
return "0" if res[0] == "0" else res
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(largest_number([10, 2]))
|
||||
print(largest_number([3, 30, 34, 5, 9]))
|
||||
print(largest_number([0, 0]))
|
||||
60
algorithms/labs/lab8/code/hash/1.py
Normal file
@@ -0,0 +1,60 @@
|
||||
class Node:
|
||||
def __init__(self, key, val):
|
||||
self.key = key
|
||||
self.val = val
|
||||
self.prev = None
|
||||
self.next = None
|
||||
|
||||
|
||||
class LRUCache:
|
||||
def __init__(self, capacity: int):
|
||||
self.cap = capacity
|
||||
self.cache = {}
|
||||
self.left = Node(0, 0)
|
||||
self.right = Node(0, 0)
|
||||
self.left.next = self.right
|
||||
self.right.prev = self.left
|
||||
|
||||
def remove(self, node):
|
||||
p, n = node.prev, node.next
|
||||
p.next = n
|
||||
n.prev = p
|
||||
|
||||
def insert(self, node):
|
||||
p, n = self.right.prev, self.right
|
||||
p.next = node
|
||||
node.prev = p
|
||||
node.next = n
|
||||
n.prev = node
|
||||
|
||||
def get(self, key: int) -> int:
|
||||
if key not in self.cache:
|
||||
return -1
|
||||
node = self.cache[key]
|
||||
self.remove(node)
|
||||
self.insert(node)
|
||||
return node.val
|
||||
|
||||
def put(self, key: int, value: int) -> None:
|
||||
if key in self.cache:
|
||||
self.remove(self.cache[key])
|
||||
node = Node(key, value)
|
||||
self.cache[key] = node
|
||||
self.insert(node)
|
||||
if len(self.cache) > self.cap:
|
||||
lru = self.left.next
|
||||
self.remove(lru)
|
||||
del self.cache[lru.key]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
lru = LRUCache(2)
|
||||
lru.put(1, 1)
|
||||
lru.put(2, 2)
|
||||
print(lru.get(1))
|
||||
lru.put(3, 3)
|
||||
print(lru.get(2))
|
||||
lru.put(4, 4)
|
||||
print(lru.get(1))
|
||||
print(lru.get(3))
|
||||
print(lru.get(4))
|
||||
43
algorithms/labs/lab8/code/hash/2.py
Normal file
@@ -0,0 +1,43 @@
|
||||
class TrieNode:
|
||||
def __init__(self):
|
||||
self.children = {}
|
||||
self.is_end = False
|
||||
|
||||
|
||||
class Trie:
|
||||
def __init__(self):
|
||||
self.root = TrieNode()
|
||||
|
||||
def insert(self, word):
|
||||
node = self.root
|
||||
for ch in word:
|
||||
if ch not in node.children:
|
||||
node.children[ch] = TrieNode()
|
||||
node = node.children[ch]
|
||||
node.is_end = True
|
||||
|
||||
def search(self, word):
|
||||
node = self.root
|
||||
for ch in word:
|
||||
if ch not in node.children:
|
||||
return False
|
||||
node = node.children[ch]
|
||||
return node.is_end
|
||||
|
||||
def startsWith(self, prefix):
|
||||
node = self.root
|
||||
for ch in prefix:
|
||||
if ch not in node.children:
|
||||
return False
|
||||
node = node.children[ch]
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
t = Trie()
|
||||
t.insert("apple")
|
||||
print(t.search("apple"))
|
||||
print(t.search("app"))
|
||||
print(t.startsWith("app"))
|
||||
t.insert("app")
|
||||
print(t.search("app"))
|
||||
50
algorithms/labs/lab8/code/hash/3.py
Normal file
@@ -0,0 +1,50 @@
|
||||
import heapq
|
||||
|
||||
|
||||
class Twitter:
|
||||
def __init__(self):
|
||||
self.time = 0
|
||||
self.tweets = {}
|
||||
self.follows = {}
|
||||
|
||||
def postTweet(self, userId, tweetId):
|
||||
self.time += 1
|
||||
if userId not in self.tweets:
|
||||
self.tweets[userId] = []
|
||||
self.tweets[userId].append((-self.time, tweetId))
|
||||
|
||||
def getNewsFeed(self, userId):
|
||||
heap = []
|
||||
if userId in self.tweets:
|
||||
heap.extend(self.tweets[userId][-10:])
|
||||
if userId in self.follows:
|
||||
for v in self.follows[userId]:
|
||||
if v in self.tweets:
|
||||
heap.extend(self.tweets[v][-10:])
|
||||
heapq.heapify(heap)
|
||||
res = []
|
||||
while heap and len(res) < 10:
|
||||
res.append(heapq.heappop(heap)[1])
|
||||
return res
|
||||
|
||||
def follow(self, followerId, followeeId):
|
||||
if followerId == followeeId:
|
||||
return
|
||||
if followerId not in self.follows:
|
||||
self.follows[followerId] = set()
|
||||
self.follows[followerId].add(followeeId)
|
||||
|
||||
def unfollow(self, followerId, followeeId):
|
||||
if followerId in self.follows and followeeId in self.follows[followerId]:
|
||||
self.follows[followerId].remove(followeeId)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
tw = Twitter()
|
||||
tw.postTweet(1, 5)
|
||||
print(tw.getNewsFeed(1))
|
||||
tw.follow(1, 2)
|
||||
tw.postTweet(2, 6)
|
||||
print(tw.getNewsFeed(1))
|
||||
tw.unfollow(1, 2)
|
||||
print(tw.getNewsFeed(1))
|
||||
38
algorithms/labs/lab8/code/search/1.py
Normal file
@@ -0,0 +1,38 @@
|
||||
def exist(board, word):
|
||||
rows, cols = len(board), len(board[0])
|
||||
visited = set()
|
||||
|
||||
def dfs(r, c, k):
|
||||
if k == len(word):
|
||||
return True
|
||||
if (
|
||||
r < 0
|
||||
or r >= rows
|
||||
or c < 0
|
||||
or c >= cols
|
||||
or (r, c) in visited
|
||||
or board[r][c] != word[k]
|
||||
):
|
||||
return False
|
||||
visited.add((r, c))
|
||||
ok = (
|
||||
dfs(r + 1, c, k + 1)
|
||||
or dfs(r - 1, c, k + 1)
|
||||
or dfs(r, c + 1, k + 1)
|
||||
or dfs(r, c - 1, k + 1)
|
||||
)
|
||||
visited.remove((r, c))
|
||||
return ok
|
||||
|
||||
for r in range(rows):
|
||||
for c in range(cols):
|
||||
if dfs(r, c, 0):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
board = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]]
|
||||
print(exist(board, "ABCCED"))
|
||||
print(exist(board, "SEE"))
|
||||
print(exist(board, "ABCB"))
|
||||
22
algorithms/labs/lab8/code/search/2.py
Normal file
@@ -0,0 +1,22 @@
|
||||
def search_rotated(nums, target):
|
||||
l, r = 0, len(nums) - 1
|
||||
while l <= r:
|
||||
m = (l + r) // 2
|
||||
if nums[m] == target:
|
||||
return m
|
||||
if nums[m] >= nums[l]:
|
||||
if nums[l] <= target < nums[m]:
|
||||
r = m - 1
|
||||
else:
|
||||
l = m + 1
|
||||
else:
|
||||
if nums[m] < target <= nums[r]:
|
||||
l = m + 1
|
||||
else:
|
||||
r = m - 1
|
||||
return -1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(search_rotated([4, 5, 6, 7, 0, 1, 2], 0))
|
||||
print(search_rotated([4, 5, 6, 7, 0, 1, 2], 3))
|
||||
31
algorithms/labs/lab8/code/search/3.py
Normal file
@@ -0,0 +1,31 @@
|
||||
def search_matrix(matrix, target):
|
||||
if not matrix or not matrix[0]:
|
||||
return False
|
||||
top, bot = 0, len(matrix) - 1
|
||||
while top <= bot:
|
||||
mid = (top + bot) // 2
|
||||
if matrix[mid][0] <= target <= matrix[mid][-1]:
|
||||
row = mid
|
||||
break
|
||||
if target < matrix[mid][0]:
|
||||
bot = mid - 1
|
||||
else:
|
||||
top = mid + 1
|
||||
else:
|
||||
return False
|
||||
l, r = 0, len(matrix[row]) - 1
|
||||
while l <= r:
|
||||
m = (l + r) // 2
|
||||
if matrix[row][m] == target:
|
||||
return True
|
||||
if matrix[row][m] < target:
|
||||
l = m + 1
|
||||
else:
|
||||
r = m - 1
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
|
||||
print(search_matrix(matrix, 3))
|
||||
print(search_matrix(matrix, 13))
|
||||
25
algorithms/labs/lab8/code/sorting/1.py
Normal file
@@ -0,0 +1,25 @@
|
||||
def three_sum(nums):
|
||||
res = []
|
||||
nums.sort()
|
||||
for i in range(len(nums)):
|
||||
if i > 0 and nums[i] == nums[i - 1]:
|
||||
continue
|
||||
j = i + 1
|
||||
k = len(nums) - 1
|
||||
while j < k:
|
||||
s = nums[i] + nums[j] + nums[k]
|
||||
if s > 0:
|
||||
k -= 1
|
||||
elif s < 0:
|
||||
j += 1
|
||||
else:
|
||||
res.append([nums[i], nums[j], nums[k]])
|
||||
j += 1
|
||||
while j < k and nums[j] == nums[j - 1]:
|
||||
j += 1
|
||||
return res
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
nums = [-1, 0, 1, 2, -1, -4]
|
||||
print(three_sum(nums))
|
||||
20
algorithms/labs/lab8/code/sorting/2.py
Normal file
@@ -0,0 +1,20 @@
|
||||
def sort_colors(nums):
|
||||
low = 0
|
||||
mid = 0
|
||||
high = len(nums) - 1
|
||||
while mid <= high:
|
||||
if nums[mid] == 0:
|
||||
nums[low], nums[mid] = nums[mid], nums[low]
|
||||
low += 1
|
||||
mid += 1
|
||||
elif nums[mid] == 1:
|
||||
mid += 1
|
||||
else:
|
||||
nums[mid], nums[high] = nums[high], nums[mid]
|
||||
high -= 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
nums = [2, 0, 2, 1, 1, 0]
|
||||
sort_colors(nums)
|
||||
print(nums)
|
||||
13
algorithms/labs/lab8/code/sorting/3.py
Normal file
@@ -0,0 +1,13 @@
|
||||
def wiggle_sort(nums):
|
||||
nums.sort()
|
||||
mid = (len(nums) + 1) // 2
|
||||
left = nums[:mid][::-1]
|
||||
right = nums[mid:][::-1]
|
||||
nums[::2] = left
|
||||
nums[1::2] = right
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
nums = [1, 5, 1, 1, 6, 4]
|
||||
wiggle_sort(nums)
|
||||
print(nums)
|
||||