upd
This commit is contained in:
15
algorithms/labs/lab8/code/comp/1.py
Normal file
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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)
|
||||
Reference in New Issue
Block a user