算法学习记录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.mzph.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…