Appearance
question:from collections import defaultdict, deque from typing import List, Dict, Union def find_switch_order(test_cases: List[Dict[str, Union[int, List[tuple]]]]) -> List[Union[List[int], str]]: Determine the order in which switches should be deactivated based on given dependency rules. >>> find_switch_order([{'N': 3, 'M': 2, 'edges': [(1, 2), (2, 3)]}]) [[1, 2, 3]] >>> find_switch_order([{'N': 4, 'M': 3, 'edges': [(1, 2), (2, 3), (3, 1)]}]) ["IMPOSSIBLE"] Args: test_cases (List[Dict[str, Union[int, List[tuple]]]]): A list of test cases where each test case is a dictionary with: - N: Number of switches (nodes) - M: Number of dependency rules (edges) - edges: List of dependency rules as tuples (u, v) indicating that switch u must be deactivated before switch v. Returns: List[Union[List[int], str]]: For each test case, returns the sequence of switch deactivation or "IMPOSSIBLE" if no valid sequence exists.
answer:from collections import defaultdict, deque def find_switch_order(test_cases): def topological_sort(N, graph, in_degree): queue = deque() result = [] # Initialize queue with nodes having in-degree 0 for i in range(1, N + 1): if in_degree[i] == 0: queue.append(i) while queue: node = queue.popleft() result.append(node) for neighbor in graph[node]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 0: queue.append(neighbor) if len(result) == N: return result else: return "IMPOSSIBLE" output = [] for case in test_cases: N, M = case['N'], case['M'] edges = case['edges'] graph = defaultdict(list) in_degree = [0] * (N + 1) for u, v in edges: graph[u].append(v) in_degree[v] += 1 output.append(topological_sort(N, graph, in_degree)) return output # Sample Usage test_cases = [ {'N': 3, 'M': 2, 'edges': [(1, 2), (2, 3)]}, {'N': 4, 'M': 3, 'edges': [(1, 2), (2, 3), (3, 1)]} ] print(find_switch_order(test_cases)) # Expected output: [[1, 2, 3], "IMPOSSIBLE"]
question:def can_transform(initial_sequence, target_sequence): Returns "Yes" if it is possible to transform initial_sequence into target_sequence using the allowed operations, otherwise returns "No". >>> can_transform([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) 'Yes' >>> can_transform([4, 3, 2], [1, 5, 2]) 'No' >>> can_transform([7, -8, 9, 10], [-8, 7, 10, 9]) 'Yes' >>> can_transform([1, 3, 5, 7, 9, 2], [2, 4, 6, 8, 10, 1]) 'No' >>> can_transform([1, 1, 1], [1, 1, 1]) 'Yes' >>> can_transform([-1, -2, -3], [-3, -2, -1]) 'Yes'
answer:def can_transform(initial_sequence, target_sequence): Returns "Yes" if it is possible to transform initial_sequence into target_sequence using the allowed operations, otherwise returns "No". if sorted(initial_sequence) == sorted(target_sequence): return "Yes" return "No" # Example usage if __name__ == "__main__": import sys input = sys.stdin.read data = input().split() N = int(data[0]) initial_sequence = list(map(int, data[1:N+1])) target_sequence = list(map(int, data[N+1:2*N+1])) print(can_transform(initial_sequence, target_sequence))
question:from typing import List def minimum_transfers(L: int, lines: List[List[str]], start: str, destination: str) -> int: Given the number of subway lines, list of lines with stations, and starting and destination stations, this function calculates the minimum number of transfers needed to travel from start to destination. >>> minimum_transfers(3, [["S1", "S2", "S3", "S4", "S5", "S6", "S7"], ["A", "S4", "S8", "S9", "B"], ["C", "D", "S5", "G", "H"]], "S1", "S9") 1 >>> minimum_transfers(2, [["X1", "Y1", "Z1"], ["Z1", "A1", "B1"]], "X1", "B1") 1 >>> minimum_transfers(1, [["P", "Q", "R", "S"]], "P", "S") 0 >>> minimum_transfers(3, [["S1", "S2", "S3", "S4", "S5", "S6", "S7"], ["A", "S4", "S8", "S9", "B"], ["C", "D", "S5", "G", "H"]], "S5", "S5") 0 >>> minimum_transfers(2, [["S1", "S2", "S3", "S4"], ["A", "B"]], "S2", "S4") 0
answer:from collections import deque, defaultdict def minimum_transfers(L, lines, start, destination): Given the number of subway lines, list of lines with stations, and starting and destination stations, this function calculates the minimum number of transfers needed to travel from start to destination. if start == destination: return 0 # Create a graph where nodes are stations and edges are lines between them station_to_lines = defaultdict(set) line_adjacency = defaultdict(set) for line_id, stations in enumerate(lines): for station in stations: station_to_lines[station].add(line_id) for other_station in stations: if other_station != station: line_adjacency[station].add(other_station) # BFS to find the shortest path in terms of transfers queue = deque([(start, 0)]) visited = set([start]) while queue: current_station, transfers = queue.popleft() if current_station == destination: return transfers - 1 # Subtract one because we start on one of the lines for line in station_to_lines[current_station]: for next_station in lines[line]: if next_station not in visited: visited.add(next_station) queue.append((next_station, transfers + 1)) return -1 # If no path is found
question:def group_check(s: str) -> bool: Returns True if the sequence of braces in the string is valid, otherwise returns False. The braces considered are [], {}, and (). >>> group_check("([]){}") True >>> group_check("[(])") False >>> group_check("{[()]}") True >>> group_check("((()))") True >>> group_check("([)]") False def test_group_check(): Unit test for group_check function. assert group_check("([]){}") == True assert group_check("[(])") == False assert group_check("{[()]}") == True assert group_check("((()))") == True assert group_check("([)]") == False assert group_check("") == True assert group_check("{[(((([]))))]}") == True assert group_check("({[]})") == True assert group_check("[") == False assert group_check("]") == False assert group_check("{[}") == False
answer:def group_check(s): Returns True if the sequence of braces in the string is valid, otherwise returns False. The braces considered are [], {}, and (). # Stack to keep track of opening braces stack = [] # Dictionary mapping opening braces to their corresponding closing braces matching_brace = {')': '(', '}': '{', ']': '['} for char in s: if char in matching_brace: # If the current char is a closing brace, check if it matches the latest opening brace if stack and stack[-1] == matching_brace[char]: stack.pop() else: return False else: # If the current char is an opening brace, push it to the stack stack.append(char) return not stack