算法學習記錄4

L2-012 關于堆的判斷
def checkHeap(heap, target):if target == 0:return heapif heap[target] < heap[(target - 1) // 2]:temp = heap[target]heap[target] = heap[(target - 1) // 2]heap[(target - 1) // 2] = tempheap = checkHeap(heap, (target - 1) // 2)return heapdef heapInsert(heap, value, _index):heap[_index] = valuereturn checkHeap(heap, _index)n, m = map(int, input().split())
heap = [None for i in range(n)]
values = list(map(int, input().split()))
for i, item in enumerate(values):heap = heapInsert(heap, item, i)
for i in range(m):command_words = input().split()if 'root' in command_words:print('T') if heap[0] == int(command_words[0]) else print('F')elif 'siblings' in command_words:print('T') if ((heap.index(int(command_words[0])) - 1) // 2) == ((heap.index(int(command_words[2])) - 1) // 2) else print('F')elif 'parent' in command_words:print('T') if heap.index(int(command_words[0])) == ((heap.index(int(command_words[-1])) - 1) // 2) else print('F')else:print('T') if heap.index(int(command_words[-1])) == (heap.index(int(command_words[0])) - 1) // 2 else print('F')

L2-013 紅色警報
def find_components(n, edges):visited = [False] * ngraph = [[] for _ in range(n)]for u, v in edges:graph[u].append(v)graph[v].append(u)def dfs(node):stack = [node]while stack:u = stack.pop()for v in graph[u]:if not visited[v]:visited[v] = Truestack.append(v)count = 0for i in range(n):if not visited[i]:count += 1visited[i] = Truedfs(i)return countdef main():import sysinput = sys.stdin.readdata = input().splitlines()n, m = map(int, data[0].split())edges = [list(map(int, data[i].split())) for i in range(1, m + 1)]k = int(data[m + 1])occupied_cities = list(map(int, data[m + 2].split()))# 先計算原始的連通分量數original_components = find_components(n, edges)# 模擬每個城市被攻占lost_cities = set()for i, city in enumerate(occupied_cities):lost_cities.add(city)# 重新構建圖,排除被攻占的城市new_edges = [edge for edge in edges if edge[0] not in lost_cities and edge[1] not in lost_cities]new_components = find_components(n, new_edges)if new_components > original_components:print(f"Red Alert: City {city} is lost!")else:print(f"City {city} is lost.")original_components = new_componentsif len(lost_cities) == n:print("Game Over.")if __name__ == "__main__":main()

L2-015 互評成績
def calculate_final_score(scores, k):final_scores = []for student_scores in scores:student_scores.sort()trimmed_scores = student_scores[1:k-1]  # 去掉最高分和最低分final_score = sum(trimmed_scores) / len(trimmed_scores)final_scores.append(final_score)return final_scoresdef main():N, k, M = map(int, input().split())  # 學生總數、每份作業的評審數、需要輸出的學生數scores = []for _ in range(N):student_scores = list(map(int, input().split()))scores.append(student_scores)final_scores = calculate_final_score(scores, k)final_scores.sort(reverse=True)  # 非遞減順序排序for i in range(M):print("{:.3f}".format(final_scores[i]), end=" ")if __name__ == "__main__":main()

L2-016 愿天下有情人都是失散多年的兄妹
import syssex = {}  # 記錄性別
vec = {}  # 存關系圖def dfs(x, num):  # 從多少號,多少代開始 ,以0開始global flagif num >= 4:returnvec[x] = vec.get(x, [])for i in range(len(vec[x])):vis[vec[x][i]] = vis.get(vec[x][i], 0)if not vis[vec[x][i]]:vis[vec[x][i]] = 1  # 標記出現的人dfs(vec[x][i], num + 1)else:flag = 1  # 是近親returnn = int(sys.stdin.readline())
for i in range(n):num, sexx, dad, mom = sys.stdin.readline().split()sex[num] = sexxvec[num] = vec.get(num, [])if dad != "-1":vec[num].append(dad)sex[dad] = 'M'if mom != "-1":vec[num].append(mom)sex[mom] = "F"
num = int(input())
for i in range(num):person1, person2 = sys.stdin.readline().split()if sex[person1] == sex[person2]:print("Never Mind")else:vis = {}  # 標記是否訪問flag = 0vis[person1] = vis[person2] = 1dfs(person1, 0)dfs(person2, 0)if flag:print("No")else:print("Yes")
L2-017 人以群分 
def sum_range(arr, start, end):return sum(arr[start:end + 1])def main():# 讀取輸入n = int(input())activity_levels = list(map(int, input().split()))# 對活躍度排序activity_levels.sort()# 確定分組if n % 2 == 0:n1 = n2 = n // 2else:n1 = n // 2n2 = n // 2 + 1# 計算活躍度差異sum_outgoing = sum_range(activity_levels, n // 2, n - 1)sum_introverted = sum_range(activity_levels, 0, n // 2 - 1)diff = abs(sum_outgoing - sum_introverted)# 輸出結果print(f"Outgoing #: {n2}")print(f"Introverted #: {n1}")print(f"Diff = {diff}")if __name__ == "__main__":main()

L2-018 多項式A除以B
def display(poly):items = [(exp, coeff) for exp, coeff in sorted(poly.items(), reverse=True) if abs(coeff) >= 0.05]if not items:return "0 0 0.0"result = [str(len(items))] + [f"{exp} {coeff:.1f}" for exp, coeff in items]return ' '.join(result)def parse_input():import sysinput = sys.stdin.read().split()c1, c2 = {}, {}idx = 1m = int(input[0])for _ in range(m):exp = int(input[idx])coeff = float(input[idx + 1])c1[exp] = coeffidx += 2n = int(input[idx])idx += 1for _ in range(n):exp = int(input[idx])coeff = float(input[idx + 1])c2[exp] = coeffidx += 2return c1, c2def polynomial_division(c1, c2):c3 = {}if c1 and c2:max_exp1 = max(c1.keys())max_exp2 = max(c2.keys())while max_exp1 >= max_exp2:if max_exp1 in c1 and abs(c1[max_exp1]) >= 0.05:exp_diff = max_exp1 - max_exp2ratio = c1[max_exp1] / c2[max_exp2]c3[exp_diff] = ratiofor i in c2:exp = exp_diff + ic1[exp] = c1.get(exp, 0) - c2[i] * ratioif abs(c1[exp]) < 0.05:del c1[exp]while max_exp1 in c1 and abs(c1[max_exp1]) < 0.05:del c1[max_exp1]max_exp1 -= 1max_exp1 -= 1return c3, c1def main():c1, c2 = parse_input()c3, c1_remainder = polynomial_division(c1, c2)print(display(c3))print(display(c1_remainder))if __name__ == "__main__":main()

L2-020 功夫傳人
k,z,r = input().split()
k = int(k)
z,r = float(z),float(r)
arr = [0]*k
arr[0] = z
D = [] #用來存儲得道者
c = [[] for i in range(k)]
ant = 0
for i in range(k):b = list(map(int,input().split()))if b[0] != 0:temp = arr[i] - arr[i] * r * 0.01for x in b[1:]:arr[x] = tempc[i].extend(b[1:])else:if arr[i] == 0:for i in range(k):if c[i] != []:for j in c[i]:arr[j] = arr[i] - arr[i] * r * 0.01arr[i] = arr[i] * b[1]ant += arr[i]
print(int(ant))
L2-021 點贊狂魔

def find_top_like_maniacs():N = int(input())  # 從終端接收用戶數like_data = {}for _ in range(N):entry = input()  # 從終端接收每個用戶的點贊數據parts = entry.split()name = parts[0]K = int(parts[1])  # 點贊總次數tags = set(parts[2:])  # 使用集合來存儲不重復的標簽unique_tags_count = len(tags)  # 不重復標簽的數量avg_likes_per_tag = K / unique_tags_count  # 計算點贊平均值like_data[name] = (unique_tags_count, avg_likes_per_tag)# 根據不重復標簽數降序排序,相同情況下根據點贊平均值升序排序sorted_users = sorted(like_data.items(), key=lambda x: (-x[1][0], x[1][1]))# 提取前三名用戶,如果不足三人用'-'填充top_three = [user[0] for user in sorted_users[:3]]while len(top_three) < 3:top_three.append('-')# 輸出結果print(' '.join(top_three))# 調用函數執行
find_top_like_maniacs()
L2-022 重排鏈表
def read_input():first_address, n = input().split()n = int(n)nodes = {}for _ in range(n):address, key, next_address = input().split()nodes[address] = {'key': int(key), 'next': next_address}return first_address, nodesdef remove_duplicates(first_address, nodes):current_address = first_addressunique_values = set()removed_nodes = {}prev_address = Noneunique_list = Nonewhile current_address != "-1":node = nodes[current_address]abs_key = abs(node['key'])if abs_key in unique_values:# Move node to removed listremoved_nodes[current_address] = nodeif prev_address:nodes[prev_address]['next'] = node['next']else:unique_values.add(abs_key)if unique_list is None:unique_list = current_addressprev_address = current_addresscurrent_address = node['next']return unique_list, removed_nodesdef print_list(start_address, nodes):current_address = start_addresswhile current_address != "-1":node = nodes[current_address]next_address = node['next']print(f"{current_address} {node['key']} {next_address}")current_address = next_addressdef main():first_address, nodes = read_input()unique_list_start, removed_nodes = remove_duplicates(first_address, nodes)print_list(unique_list_start, nodes)if removed_nodes:for address, node in removed_nodes.items():node['next'] = "-1"removed_list_start = list(removed_nodes.keys())[0]current_address = removed_list_startwhile True:next_address = removed_nodes[current_address]['next']if next_address == "-1":breakcurrent_address = next_addressprint_list(removed_list_start, removed_nodes)if __name__ == "__main__":main()

L2-023 圖著色問題
def is_valid_coloring(V, edges, coloring):for u, v in edges:if coloring[u - 1] == coloring[v - 1]:return Falsereturn Truedef main():import sysinput = sys.stdin.readdata = input().split()index = 0V = int(data[index])E = int(data[index + 1])K = int(data[index + 2])index += 3edges = []for _ in range(E):u = int(data[index])v = int(data[index + 1])edges.append((u, v))index += 2N = int(data[index])index += 1results = []for _ in range(N):coloring = list(map(int, data[index:index + V]))index += Vif is_valid_coloring(V, edges, coloring):results.append("Yes")else:results.append("No")for result in results:print(result)if __name__ == "__main__":main()

L2-026 小字輩
def main():n = int(input())father = list(map(int, input().split()))generations = [0] * (n+1)min_generation = float('inf')# 計算每個成員到老祖宗的輩分for i in range(1, n+1):if father[i-1] == -1:generations[i] = 1else:generations[i] = generations[father[i-1]] + 1min_generation = min(min_generation, generations[i])# 找到擁有最小輩分的成員編號min_generation_members = [i for i in range(1, n+1) if generations[i] == min_generation]# 輸出結果print(min_generation)print(' '.join(map(str, min_generation_members)))if __name__ == "__main__":main()
L2-032 彩虹瓶
def can_complete_task(n, m, shipment):stack = []  # 臨時貨架,使用列表模擬棧next_color = 1  # 下一個需要裝填的彩球顏色for color in shipment:if color == next_color:next_color += 1# 檢查棧頂是否有連續可以裝填的顏色while stack and stack[-1] == next_color:stack.pop()next_color += 1else:# 放置到棧上stack.append(color)# 檢查棧是否超出了容量if len(stack) > m:return "NO"# 檢查是否所有顏色都已裝填if next_color - 1 == n:return "YES"else:return "NO"# 輸入處理部分
import sysinput = sys.stdin.read
data = input().split()
n, m, k = map(int, data[:3])
results = []# 對每一個發貨順序進行檢查
index = 3
for _ in range(k):shipment = list(map(int, data[index:index + n]))index += nresult = can_complete_task(n, m, shipment)results.append(result)# 輸出結果
for result in results:print(result)

L2-033 簡單計算器
def calculator(N, numbers, operators):stack_numbers = []stack_operators = []# Push numbers and operators to respective stacksfor num in numbers:stack_numbers.append(num)for op in operators:stack_operators.append(op)while stack_operators:if len(stack_numbers) < 2:breakn1 = stack_numbers.pop()n2 = stack_numbers.pop()op = stack_operators.pop()if op == '+':result = n2 + n1elif op == '-':result = n2 - n1elif op == '*':result = n2 * n1elif op == '/':if n1 == 0:print(f"ERROR: {n2}/0")returnresult = n2 // n1  # Use integer divisionelse:raise ValueError(f"Unknown operator: {op}")stack_numbers.append(result)if len(stack_numbers) == 1:print(stack_numbers[0])else:raise ValueError("Invalid computation process")# Read input
import sysinput = sys.stdin.read
data = input().split()N = int(data[0])
numbers = list(map(int, data[1:N + 1]))
operators = data[N + 1:N + N]# Execute the calculator function
calculator(N, numbers, operators)
L2-035 完全二叉樹的層序遍歷 
class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = Nonedef build_tree(postorder, start, end, total_nodes):if start > end:return None# 后序遍歷的最后一個節點是根節點root_val = postorder[end]root = TreeNode(root_val)if start == end:return root# 確定完全二叉樹最后一層的節點數levels_full = 0count = 1while count * 2 - 1 < total_nodes:levels_full += 1count *= 2# 最后一層之前的所有節點數last_full_level_count = count // 2 - 1# 最后一層的節點數last_level_count = total_nodes - (count - 1)left_size = min(end - start, last_full_level_count)if last_level_count > count // 2:left_size = last_full_level_count + count // 2else:left_size = last_full_level_count + last_level_count# 遞歸構建左子樹和右子樹root.left = build_tree(postorder, start, start + left_size - 1, left_size)root.right = build_tree(postorder, start + left_size, end - 1, total_nodes - left_size - 1)return rootdef level_order_traversal(root):if not root:return []from collections import dequequeue = deque([root])result = []while queue:node = queue.popleft()result.append(node.val)if node.left:queue.append(node.left)if node.right:queue.append(node.right)return resultdef main():node_count = int(input())postorder = list(map(int, input().split()))if node_count == 0:print("")return# 構建樹root = build_tree(postorder, 0, node_count - 1, node_count)# 層序遍歷result = level_order_traversal(root)# 輸出結果print(" ".join(map(str, result)))if __name__ == '__main__':main()
L3-001 湊零錢
def dfs(coins, current_sum, index, path, results, used):if current_sum > M:returnif current_sum == M:results.append(path.copy())returnfor i in range(index, len(coins)):if not used[i]:used[i] = Truepath.append(coins[i])dfs(coins, current_sum + coins[i], i + 1, path, results, used)path.pop()used[i] = Falseif results:returndef solve():global MN, M = map(int, input().split())coins = list(map(int, input().split()))coins.sort()if sum(coins) < M:print("No Solution")returnresults = []used = [False] * Ndfs(coins, 0, 0, [], results, used)if not results:print("No Solution")else:print(" ".join(map(str, results[0])))solve()
L3-002 特殊堆棧
import sys
import bisectdef main():n = int(sys.stdin.readline().strip())stack = []sorted_keys = []def push(key):stack.append(key)bisect.insort(sorted_keys, key)def pop():if not stack:return "Invalid"top = stack.pop()idx = bisect.bisect_left(sorted_keys, top)sorted_keys.pop(idx)return topdef peek_median():if not stack:return "Invalid"median_index = (len(sorted_keys) - 1) // 2return sorted_keys[median_index]for _ in range(n):command = sys.stdin.readline().strip().split()if command[0] == "Push":push(int(command[1]))elif command[0] == "Pop":print(pop())elif command[0] == "PeekMedian":print(peek_median())if __name__ == "__main__":main()
L3-006 迎風一刀斬
def normalize_polygon(vertices):# 找到最左下的頂點,并根據這個頂點重新排序頂點,以確保逆時針方向start = min(range(len(vertices)), key=lambda i: (vertices[i][1], vertices[i][0]))sorted_vertices = vertices[start:] + vertices[:start]if (sorted_vertices[1][0] - sorted_vertices[0][0]) * (sorted_vertices[2][1] - sorted_vertices[0][1]) < (sorted_vertices[2][0] - sorted_vertices[0][0]) * (sorted_vertices[1][1] - sorted_vertices[0][1]):sorted_vertices = list(reversed(sorted_vertices))return sorted_verticesdef rotate_polygon(vertices, angle):# 旋轉多邊形頂點,angle是90度的倍數if angle == 90:return [(v[1], -v[0]) for v in vertices]elif angle == 180:return [(-v[0], -v[1]) for v in vertices]elif angle == 270:return [(-v[1], v[0]) for v in vertices]return verticesdef reflect_polygon(vertices):# 鏡像多邊形頂點return [(-v[0], v[1]) for v in vertices]def translate_to_origin(vertices):# 將多邊形平移到原點min_x = min(v[0] for v in vertices)min_y = min(v[1] for v in vertices)return [(v[0] - min_x, v[1] - min_y) for v in vertices]def polygon_transforms(vertices):# 生成所有變換transformations = []for angle in [0, 90, 180, 270]:rotated = rotate_polygon(vertices, angle)transformations.append(translate_to_origin(rotated))reflected = reflect_polygon(rotated)transformations.append(translate_to_origin(reflected))return transformationsdef match_polygons(p1, p2):# 檢查兩個多邊形是否可以匹配p1_transforms = polygon_transforms(p1)p2_transforms = polygon_transforms(p2)return any(t1 == t2 for t1 in p1_transforms for t2 in p2_transforms)# 輸入和處理邏輯
n = int(input())
results = []
for _ in range(n):k1, *coords1 = map(int, input().split())p1 = [(coords1[i], coords1[i+1]) for i in range(0, 2*k1, 2)]k2, *coords2 = map(int, input().split())p2 = [(coords2[i], coords2[i+1]) for i in range(0, 2*k2, 2)]p1 = normalize_polygon(p1)p2 = normalize_polygon(p2)if match_polygons(p1, p2):results.append("YES")else:results.append("NO")for result in results:print(result)

L3-007 天梯地圖
def floyd_warshall(graph):n = len(graph)dist = [[float('inf')] * n for _ in range(n)]next_node = [[-1] * n for _ in range(n)] # to store next node in shortest pathfor i in range(n):dist[i][i] = 0for u in range(n):for v, d in graph[u]:dist[u][v] = dnext_node[u][v] = vfor k in range(n):for i in range(n):for j in range(n):if dist[i][k] + dist[k][j] < dist[i][j]:dist[i][j] = dist[i][k] + dist[k][j]next_node[i][j] = next_node[i][k]return dist, next_nodedef get_shortest_path(next_node, start, end):path = []while start != end:path.append(start)start = next_node[start][end]path.append(end)return pathdef main():N, M = map(int, input().split())graph = [[] for _ in range(N)]for _ in range(M):V1, V2, one_way, length, time = map(int, input().split())graph[V1].append((V2, time))if not one_way:graph[V2].append((V1, time))start, end = map(int, input().split())dist, next_node = floyd_warshall(graph)fastest_time = dist[start][end]shortest_path_time = fastest_timeshortest_path = get_shortest_path(next_node, start, end)shortest_distance = float('inf')for i in range(N):if i != start and i != end:shortest_distance = min(shortest_distance, dist[start][i] + dist[i][end])fastest_time_path = get_shortest_path(next_node, start, end)print("Time = {}: {}".format(fastest_time, ' => '.join(map(str, fastest_time_path))))print("Distance = {}: {}".format(shortest_distance, ' => '.join(map(str, shortest_path))))if __name__ == "__main__":main()
L3-008 喊山
def find_farthest_mountain(n, m, k, edges, queries):# 構建山頭之間的連接關系字典connections = {}for edge in edges:a, b = edgeif a not in connections:connections[a] = []if b not in connections:connections[b] = []connections[a].append(b)connections[b].append(a)# 定義深度優先搜索函數def dfs(node, visited):visited.add(node)farthest = nodefor neighbor in connections.get(node, []):if neighbor not in visited:farthest = max(farthest, dfs(neighbor, visited))return farthest# 遍歷查詢列表,找出每個查詢的最遠連鎖山頭result = []for query in queries:if query in connections:farthest_mountain = dfs(query, set())else:farthest_mountain = 0result.append(farthest_mountain)return result# 讀取輸入
n, m, k = map(int, input().split())
edges = [tuple(map(int, input().split())) for _ in range(m)]
queries = list(map(int, input().split()))# 調用函數并輸出結果
result = find_farthest_mountain(n, m, k, edges, queries)
for res in result:print(res)

L3-010 是否完全二叉搜索樹
tree = [0] * (1 << 20)
height = [0] * (1 << 20)def BST(a, num):global treeif tree[a] == 0:tree[a] = numelif tree[a] < num:BST(a * 2, num)else:BST((a << 1) + 1, num)def isComplete(a, h, index, n):if a >= len(tree) or tree[a] == 0:return Trueif index >= n:return Falseleft_complete = isComplete(a * 2, h + 1, index * 2 + 1, n)right_complete = isComplete((a << 1) + 1, h + 1, index * 2 + 2, n)if not left_complete or not right_complete:return Falsereturn Truedef levelOrderTraversal(a):queue = [a]result = []while queue:current = queue.pop(0)if tree[current] != 0:result.append(tree[current])queue.extend([current * 2, (current << 1) + 1])return ' '.join(map(str, result))def main():global heightn = int(input())nums = list(map(int, input().split()))for num in nums:BST(1, num)# 計算樹的高度height[1] = 1for i in range(1, len(height)):if tree[i] != 0:if i * 2 < len(height):height[i * 2] = height[i] + 1if (i << 1) + 1 < len(height):height[(i << 1) + 1] = height[i] + 1# 判斷是否完全二叉樹并進行層序遍歷flag = isComplete(1, 1, 0, n)traversal_result = levelOrderTraversal(1)print(traversal_result)if flag:print("YES")else:print("NO")if __name__ == "__main__":main()
L4-302 拼題A打卡獎勵
def max_coins(n, m, times, coins):# 貪心預處理:按單位時間的金幣價值降序排序items = sorted(zip(times, coins), key=lambda x: -x[1] / x[0])# 初始化DP數組dp = [0] * (m + 1)# 遍歷打卡卷(已排序)for time, coin in items:# 從后往前更新DP數組for j in range(m, time - 1, -1):dp[j] = max(dp[j], dp[j - time] + coin)return dp[m]# 輸入處理部分
n, m = map(int, input().strip().split())
times = list(map(int, input().strip().split()))
coins = list(map(int, input().strip().split()))# 計算最大金幣數并輸出
result = max_coins(n, m, times, coins)
print(result)
L4-202 二叉搜索樹的2層結點統計
class TreeNode:def __init__(self, key):self.left = Noneself.right = Noneself.value = keydef insert(root, key):if root is None:return TreeNode(key)else:if root.value < key:root.right = insert(root.right, key)else:root.left = insert(root.left, key)return rootdef count_last_two_levels(root):if not root:return 0from collections import dequequeue = deque([root])level_count = []while queue:level_size = len(queue)current_level = []for _ in range(level_size):node = queue.popleft()current_level.append(node)if node.left:queue.append(node.left)if node.right:queue.append(node.right)level_count.append(len(current_level))if len(level_count) == 1:return level_count[0]else:return level_count[-1] + level_count[-2]def main():import sysinput = sys.stdin.readdata = input().split()N = int(data[0])numbers = list(map(int, data[1:N + 1]))root = Nonefor number in numbers:root = insert(root, number)result = count_last_two_levels(root)print(result)if __name__ == "__main__":main()

L4-201 出棧序列的合法性
def is_valid_sequence(m, n, sequence):stack = []current = 0  # 當前需要入棧的數字,初始化為0,表示還未開始入棧for num in sequence:if current < num:  # 如果當前需要的數字小于目標數字# 需要將 current+1 到 num 入棧while current < num:if len(stack) < m:  # 檢查是否超出棧的最大容量current += 1stack.append(current)else:return "NO"if stack and stack[-1] == num:  # 檢查棧頂元素是否為需要出棧的元素stack.pop()  # 出棧else:return "NO"  # 如果棧頂元素不是需要出棧的,那么這個序列不可能return "YES"def process_stack_operations(m, n, k, sequences):results = []for seq in sequences:results.append(is_valid_sequence(m, n, seq))return results# 輸入部分處理
import sys
input = sys.stdin.read
data = input().splitlines()first_line = data[0].split()
m = int(first_line[0])
n = int(first_line[1])
k = int(first_line[2])sequences = []
for i in range(1, k + 1):sequences.append(list(map(int, data[i].split())))# 處理每個序列,輸出結果
results = process_stack_operations(m, n, k, sequences)
for result in results:print(result)
L4-117 矩陣列平移
def is_valid_sequence(sequence):if len(sequence) == 1:return Truefor i in range(len(sequence) - 1):current = sequence[i]next_char = sequence[i + 1]if current.isupper():valid_next_lower = current.lower()valid_next_upper = chr(ord(current) + 1) if current != 'Z' else Noneif not ((next_char == valid_next_lower) or (next_char == valid_next_upper)):return Falseelse:valid_next_upper = current.upper()valid_prev_lower = chr(ord(current) - 1) if current != 'a' else Noneif not ((next_char == valid_next_upper) or (next_char == valid_prev_lower)):return Falsereturn TrueN = int(input())
for _ in range(N):student_sequence = input()print("Y" if is_valid_sequence(student_sequence) else "N")
L4-116 字母串
def is_valid_sequence(sequence):# 如果序列只有一個字符,它是合法的if len(sequence) == 1:return True# 遍歷序列中的每個字符,檢查與下一個字符的關系for i in range(len(sequence) - 1):current = sequence[i]next_char = sequence[i + 1]# 處理大寫字母的情況if current.isupper():if current != 'Z':valid_next_upper = chr(ord(current) + 1)else:valid_next_upper = Nonevalid_next_lower = current.lower()# 檢查下一個字符是否符合規則if next_char != valid_next_lower and next_char != valid_next_upper:return False# 處理小寫字母的情況else:if current != 'a':valid_prev_lower = chr(ord(current) - 1)else:valid_prev_lower = Nonevalid_next_upper = current.upper()# 檢查下一個字符是否符合規則if next_char != valid_next_upper and next_char != valid_prev_lower:return False# 如果所有字符都符合規則,返回 Truereturn True# 讀取輸入和打印輸出
N = int(input())
results = []
for _ in range(N):student_sequence = input()results.append("Y" if is_valid_sequence(student_sequence) else "N")for result in results:print(result)
L4-108 谷歌的招聘
def is_prime(n):""" 檢查整數 n 是否為素數 """if n <= 1:return Falsei = 2while i * i <= n:if n % i == 0:return Falsei += 1return Truedef main():# 通過 input 函數逐行讀取輸入a, b = map(int, input().split())s = input().strip()# 遍歷所有長度為 b 的子串for i in range(a - b + 1):s2 = s[i:i + b]n = int(s2)if is_prime(n):print(s2)return# 如果沒有找到素數print("404")if __name__ == "__main__":main()

感謝閱讀😎

有錯請指出🤠

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/43178.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/43178.shtml
英文地址,請注明出處:http://en.pswp.cn/web/43178.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

2024.7.7刷題記錄

目錄 一、849. Dijkstra求最短路 I - AcWing題庫 二、850. Dijkstra求最短路 II - AcWing題庫 根據講解視頻寫的代碼 一、849. Dijkstra求最短路 I - AcWing題庫 N 600 MAXL 10010 # 最長邊長 # 稠密圖鄰接矩陣 g [[MAXL] * N for _ in range(N)] dist [MAXL] * N …

圖片kb太大了怎么改小?修改圖片kb的方法介紹

圖片kb太大了怎么改小&#xff1f;將圖片的文件大小&#xff08;以KB為單位&#xff09;縮小可以帶來多種優點&#xff0c;但也有一些缺點需要注意。縮小圖片文件大小可以顯著減少它在硬盤或其他存儲設備上占用的空間&#xff0c;使你能夠存儲更多的圖片和其他文件。而且&#…

KIVY 3D Rotating Monkey Head?

7 Python Kivy Projects (With Full Tutorials) – Pythonista Planet KIVY 3D Rotating Monkey Head kivy 3D 旋轉猴子頭How to display rotating monkey example in a given layout. Issue #6688 kivy/kivy GitHub 3d 模型下載鏈接 P99 - Download Free 3D model by …

【Qt】QItemSelectionModel 添加選中行

1. 介紹 QItemSelectionModel 中沒有直接添加選中行的方法&#xff0c;可以通過下面的方式添加。 2. 代碼 //定義 QSqlTableModel* m_tableModel; QItemSelectionModel* m_selectionModel;//添加選中行, 全選 void addAllLine() {for(int i0; i<m_tableModel->rowCoun…

【AI大模型新型智算中心技術體系深度分析 2024】

文末有福利&#xff01; ChatGPT 系 列 大 模 型 的 發 布&#xff0c; 不 僅 引 爆 全 球 科 技 圈&#xff0c; 更 加 夯 實 了 人 工 智 能&#xff08;Artificial Intelligence, AI&#xff09;在未來改變人類生產生活方式、引發社會文明和競爭力代際躍遷的戰略性地位。當…

mysql select count返回null

注意 mysql select count返回null 下面是百度的回答 在MySQL中&#xff0c;當SELECT COUNT(*)查詢返回NULL時&#xff0c;通常意味著查詢結果為空集&#xff0c;即沒有記錄匹配查詢條件。COUNT()函數在沒有匹配行的情況下返回NULL&#xff0c;而不是0。 解決方法&#xff1a…

ImportError: xxx: cannot open shared object file: No such file or directory

一類常見錯誤&#xff1a;編譯器器無法在目錄下找到共享目標文件&#xff0c; Linux(ubuntu)中共享的庫目錄為/usr/lib/x86_64-linux-gnu&#xff0c;gcc的編譯庫 在該目錄下創建共享文件&#xff08;偽造、下載&#x1f91c;cp)即可 sudo ln -s libtiff.so.6 libtiff.so.5

昇思25天學習打卡營第11天|ResNet50圖像分類

文章目錄 昇思MindSpore應用實踐基于MindSpore的ResNet50圖像分類1、ResNet50 簡介2、數據集預處理及可視化3、構建網絡構建 Building Block構建 Bottleneck Block構建 ResNet50 網絡 4、模型訓練5、圖像分類模型推理 Reference 昇思MindSpore應用實踐 本系列文章主要用于記錄…

Emacs相關

Emacs 詳細介紹 Emacs&#xff0c;全稱 Editor MACroS&#xff0c;是一款功能強大、歷史悠久的文本編輯器。它最早由 Richard Stallman 于 1976 年開發&#xff0c;是自由軟件運動的重要組成部分。Emacs 的設計理念強調可定制性和擴展性&#xff0c;使得它不僅僅是一個編輯器&…

AsyncRequestTimeoutException

在Spring MVC中&#xff0c;當一個異步請求超過配置的最大等待時間時&#xff0c;會拋出AsyncRequestTimeoutException異常。這個異常通常是由于服務器端的處理時間超過了客戶端允許的等待時間&#xff0c;或者是服務器本身的異步處理時間配置過短導致的。 spring: mvc: async…

scrapy寫爬蟲

Scrapy是一個用于爬取網站數據并提取結構化信息的Python框架 一、Scrapy介紹 1.引擎&#xff08;Engine&#xff09; – Scrapy的引擎是控制數據流和觸發事件的核心。它管理著Spider發送的請求和接收的響應&#xff0c;以及處理Spider生成的Item。引擎是Scrapy運行的驅動力。…

基于go-zero二次開發的腳本

param$2 # 字符串風格格式為&#xff1a;DemoName model_name$(echo "${param}" | awk -F _ {for(i1;i<NF;i) $itoupper(substr($i,1,1)) tolower(substr($i,2));}1 | tr -d ) # 字符串風格格式為&#xff1a;demoName struct_name$(echo "${model_name}&qu…

ClickHouse表引擎概述

ClickHouse表引擎概述 表引擎的功能&#xff1a; 數據的存儲方式 數據的存儲位置 是否可以使用索引 是否可以使用分區 是否支持數據副本 并發數據訪問 ClickHouse在建表時必須指定表引擎。 表引擎主要分為四大類&#xff1a;MergeTree系列、Log系列、與其他存儲/處理系…

字節碼編程bytebuddy之獲取方法信息和方法入參信息

寫在前面 本文看下通過bytebuddy如何獲取方法信息和方法的入參信息。 1&#xff1a;代碼 package com.dahuyou.bytebuddy.bb;import com.dahuyou.bytebuddy.TT; import net.bytebuddy.ByteBuddy; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.implement…

【高中數學/對數函數】比較a=ln2/2,b=ln5/5的大小

【問題】 比較aln2/2,bln5/5的大小 【解答】 a-bln2/2-ln5/5(5*ln2-2*ln5)/10(ln2^5-ln5^2)/10(ln32-ln25)/10>0 所以a>b 【圖像】 如果繪出函數ylnx/x的圖像&#xff0c;再標記出a,b的位置&#xff0c;則繪出圖像如下&#xff1a; 由上圖可以看出&#xff0c;a,b兩…

隨手記:對比兩個對象不一樣的值,生成一個新的對象

diffObject(obj1, obj2) {let changeForm {}for (let key in obj1) {if (!obj1.hasOwnProperty(key) || obj1[key] ! obj2[key]) {// 新舊數據不相同的key值changeForm[key] obj1[key]}}console.log(changeForm, changeForm)},

初次用bable遍歷vue項目下的中文

利用 babel 找到 AST 中的中文 // vite-plugin-babel-transform.js const parser require(babel/parser) const traverse require(babel/traverse).default // const types require(babel/types) // const generate require(babel/generator).default const fs require(f…

【PHP小課堂】學習PHP中的字符串操作函數(二)

學習PHP中的字符串操作函數&#xff08;二&#xff09; 接下來我們繼續 PHP 中字符串函數的學習。今天學習的內容主要是帶下劃線的一些字符串函數&#xff0c;上篇文章說過&#xff0c;這些系統函數的命名是 PHP 非常令人詬病的&#xff0c;有些東西真的只能靠我們的記憶來強行…

顯卡、顯卡驅動、cuda、cuDNN之間關系

顯卡、顯卡驅動、CUDA 和 cuDNN 是構成高性能計算和深度學習環境的關鍵組件&#xff0c;它們之間有著緊密的聯系。下面是對這些組件及其關系的詳細介紹&#xff1a; 顯卡&#xff08;GPU&#xff09; 顯卡&#xff0c;全稱為圖形處理器&#xff08;Graphics Processing Unit&…

【Unity2D 2022:NPC】制作任務系統

一、接受任務 1. 編輯NPC對話腳本&#xff1a; &#xff08;1&#xff09;創建靜態布爾變量用來判斷ruby是否接受到任務 public class NPCDialog : MonoBehaviour {// 創建全局變量用來判斷ruby是否接到任務public static bool receiveTask false; } &#xff08;2&#xff…