You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python从给定数组生成闭环路径并转换为元组?

How to Generate Closed Paths Starting and Ending at 0 in Python

Hey there! Let's break down how to solve this problem exactly as you need it—using loops, converting edges to tuples, and building those clean closed paths starting and ending at 0.

First, Let's Clarify the Goal

You have a list of directed edges, and you want to find all cycle paths that start at 0, follow consecutive edges (where the end of one edge is the start of the next), and loop back to 0. Your desired output is sequences like [(0,1), (1,7), (7,0)] which maps to the node path 0→1→7→0.

Your thought to convert edges to tuples is totally solid—tuples are immutable and work great for fixed path elements. The "sorting" you're thinking of isn't a standard alphabetical/numeric sort, but arranging edges in the order they appear in the path. We can absolutely do this with loops, and I'll show you how.

Step-by-Step Solution

1. Preprocess the Edge List for Easy Lookup

First, let's turn your raw edge list into a dictionary. This will let us quickly find all nodes a given starting node points to—super helpful for building paths step by step.

# Your original edge data
edges = [[0, 1], [0, 2], [0, 8], [1, 7], [2, 9], [3, 6], [4, 3], [5, 0], [6, 0], [7, 0], [8, 4], [9, 5], [10, 10]]

# Build a lookup dict: key = start node, value = list of end nodes
node_neighbors = {}
for start, end in edges:
    if start not in node_neighbors:
        node_neighbors[start] = []
    node_neighbors[start].append(end)

2. Use a Loop-Based Stack to Find All Closed Paths

We'll use a stack (a list acting like a stack) to track the paths we're building. For each step, we'll extend the path by following edges until we loop back to 0. This is all done with loops—no recursion needed.

def find_cycles(start_node, neighbor_map):
    cycles = []
    # Stack stores tuples of (current_node_path, last_node_in_path)
    stack = [([start_node], start_node)]
    
    while stack:
        current_path, last_node = stack.pop()
        
        # Get all nodes we can go to from the last node in the path
        next_nodes = neighbor_map.get(last_node, [])
        for next_node in next_nodes:
            # Create a new path by adding the next node
            updated_path = current_path.copy()
            updated_path.append(next_node)
            
            # If we're back to the start, we've found a cycle!
            if next_node == start_node:
                # Convert the node path to edge tuples (e.g., [0,1,7,0] → [(0,1), (1,7), (7,0)])
                edge_cycle = tuple( (updated_path[i], updated_path[i+1]) for i in range(len(updated_path)-1) )
                cycles.append(edge_cycle)
            else:
                # Avoid infinite loops by skipping nodes already in the current path
                if next_node not in current_path:
                    stack.append( (updated_path, next_node) )
    
    return cycles

# Get all cycles starting and ending at 0
final_cycles = find_cycles(0, node_neighbors)

# Print the results to match your desired output
for cycle in final_cycles:
    print(f"Edge path: {list(cycle)}")
    print(f"Node path: {'-'.join(map(str, [edge[0] for edge in cycle] + [cycle[-1][1]]))}\n")

3. What This Code Does

  • We start with the initial path [0] in the stack.
  • For each iteration, we pop a path from the stack, look up all nodes we can move to from the last node in the path.
  • If moving to 0 completes the cycle, we convert the node sequence into a tuple of edges (exactly what you wanted) and add it to our results.
  • If not, we extend the path and push it back to the stack (as long as we don't loop back to a node already in the path—this prevents infinite loops).

The Output You'll Get

When you run this code, you'll get exactly the paths you were hoping for:

Edge path: [(0, 8), (8, 4), (4, 3), (3, 6), (6, 0)]
Node path: 0-8-4-3-6-0

Edge path: [(0, 2), (2, 9), (9, 5), (5, 0)]
Node path: 0-2-9-5-0

Edge path: [(0, 1), (1, 7), (7, 0)]
Node path: 0-1-7-0

Answering Your Specific Questions

  • Can we do this with loops? Yep! The solution uses a while loop and stack to build paths entirely with iterative logic.
  • Converting to tuples? The code converts each complete edge path into a tuple (you can switch back to lists if you prefer—just remove the tuple() call).
  • "Sorting" edges? Instead of sorting, we're building paths in the correct sequential order by following directed edges, which gives you the ordered edge lists you need.

内容的提问来源于stack exchange,提问作者piedz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 17:52:40