循环中if多条件组合优化:图路径生成代码重构问询
Scalable Solution for Automating Edge Addition & Validation
Absolutely, you can ditch the manual edge existence checks and automate this logic entirely—this will work for paths of any length (4 elements, 8 elements, or more) without having to write dozens of if conditions. Here's how to refactor your code cleanly:
Refactored Code
for q in range(len(aaa_binary)): if len(added) != i + 1: current_path = aaa_binary[q] # Add all nodes from the current path to the graph (safe even if they exist) g.add_nodes_from(current_path) # Generate all edges for this path, regardless of length path_edges = list(zip(current_path[:-1], current_path[1:])) # Filter only edges that don't already exist in the graph missing_edges = [edge for edge in path_edges if not g.has_edge(*edge)] # Only proceed if there are edges to add (skip if all edges already exist) if missing_edges: # Add the missing edges temporarily for edge in missing_edges: g.add_edge(*edge) # Mark this path as added temporarily added_entry = [current_path, f'p{i}'] added.append(added_entry) # Validate all existing paths (including the new one) meet the shortest path condition valid = True for entry in added: path, _ = entry start, end = path[0], path[-1] if nx.shortest_path(g, start, end) != path: valid = False break # If validation fails, roll back changes if not valid: # Remove the edges we added for edge in missing_edges: g.remove_edge(*edge) # Remove the temporary entry from added added.remove(added_entry)
Key Improvements & Explanation
- Universal Edge Generation: Using
zip(current_path[:-1], current_path[1:])automatically creates all edges for any path length. For an 8-element path, this generates 7 edges without any extra code. - Automatic Missing Edge Filtering: Instead of checking every possible combination of existing/non-existing edges, we just collect the edges that aren't already in the graph. This eliminates the need for all those manual
if g.has_edge()checks. - Unified Validation & Rollback: We add the missing edges first, then validate all paths in the
addedlist. If any path fails the shortest path condition, we roll back exactly the edges we added and remove the current path fromadded. - Scalability: This code works for paths of any length—you won't have to rewrite logic when moving from 4-element to 8-element paths (or beyond).
Why This Works
Your core requirement is to only add edges that don't exist, then ensure all paths in added still have their original path as the shortest path. By isolating the missing edges, adding them, validating, and rolling back on failure, we maintain exactly the same logic as your original code—but in a way that scales infinitely without manual condition writing.
内容的提问来源于stack exchange,提问作者Tomasz Przemski
相关产品推荐
相关产品推荐

