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

如何修改Python代码以在Pruefer Code输出中显示对应树变量名(T10、T11、T12、T13)

Solution to Add Tree Names to Pruefer Code Output

Got it, let's fix your output formatting so each Pruefer Code gets labeled with its corresponding tree variable name (T10, T11, etc.). The core issue with your original code is that your list T only stores the tree objects themselves—not the human-readable names you assigned to them (like T10). Python doesn't track variable names attached to objects at runtime, so we need to explicitly pair each tree with its name.

Modified Code

Here's an updated version that uses a list of tuples to bind each tree name to its NetworkX tree object:

from matplotlib.pyplot import figure
import networkx as nx  # Don't forget to import NetworkX if you haven't already

# Define each tree along with its name as a tuple
tree_with_names = [
    ("T10", nx.random_tree(10)),
    ("T11", nx.random_tree(11)),
    ("T12", nx.random_tree(12)),
    ("T13", nx.random_tree(13))
]

# Assume you've defined your drawing options here (e.g., node labels, colors)
opts = {"with_labels": True, "node_color": "#a8d1ff"}

for name, tree in tree_with_names:
    # Use an f-string to insert the tree name into your output
    print(f"The Pruefer Code for - {name} {pruefer_code(tree)}")
    # Generate the tree visualization as before
    fig = figure()
    axis = fig.add_subplot(111)
    nx.draw(tree, **opts, ax=axis)

How This Works

  1. Pair Names with Trees: Instead of storing just tree objects, we create tuples where the first element is the tree's name (like "T10") and the second is the tree itself. This lets us access both values during the loop.
  2. Formatted Output: F-strings (f"...") make it straightforward to insert the tree name directly into your print statement, producing the exact labeled output you want.
  3. Unchanged Visualization: The tree drawing logic stays identical—we just use the tree variable from each tuple instead of the original t.

Alternative: Using a Dictionary

If you prefer, a dictionary works equally well for mapping names to trees:

trees = {
    "T10": nx.random_tree(10),
    "T11": nx.random_tree(11),
    "T12": nx.random_tree(12),
    "T13": nx.random_tree(13)
}

for name, tree in trees.items():
    print(f"The Pruefer Code for - {name} {pruefer_code(tree)}")
    # ... visualization code remains the same

Either approach will give you the labeled Pruefer Code output you're aiming for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 08:52:29