2016-10-07 3 views
1

私はかなり新しいPythonですので、気をつけてください。これはおそらく簡単です。私は、グラフの隣接リスト表現を構築しようとしています。この特定の表現では、リストのリストを使用することに決めました。各サブリストの最初の値はテール・ノードを表し、他のすべての値はヘッド・ノードを表します。例えば、エッジ1->2, 2->3, 3->1, 1->3を有するグラフは、[[1,2,3],[2,3],[3,1]]として表される。Pythonはリストの値を変更します

このエッジリストで次のコードを実行すると、わかりにくい問題が発生します。

エッジリスト(Example.txt):

1 2 
2 3 
3 1 
3 4 
5 4 
6 4 
8 6 
6 7 
7 8 

コード:実行時に

def adjacency_list(graph): 

graph_copy = graph[:] 
g_tmp = [] 
nodes = [] 
for arc in graph_copy: 

    choice_flag_1 = arc[0] not in nodes 
    choice_flag_2 = arc[1] not in nodes 
    if choice_flag_1: 
     g_tmp.append(arc) 
     nodes.append(arc[0]) 
    else: 
     idx = [item[0] for item in g_tmp].index(arc[0]) 
     g_tmp[idx].append(arc[1]) 

    if choice_flag_2: 
     g_tmp.append([arc[1]]) 
     nodes.append(arc[1]) 

return g_tmp 


# Read input from file 
g = [] 
with open('Example.txt') as f: 
    for line in f: 
     line_split = line.split() 
     new_line = [] 
     for element in line_split: 
      new_line.append(int(element)) 
     g.append(new_line) 
print('File Read. There are: %i items.' % len(g)) 
graph = adjacency_list(g) 

、コードは、(ファイルの最後の行に第二)アーク6 7を処理し、次の行( elseステートメント内にある)7g_tmpだけでなく、graph_copyおよび。

idx = [item[0] for item in g_tmp].index(arc[0]) 
g_tmp[idx].append(arc[1]) 

何が起こっているか

ありがとうございました!

J

P.私はPython 3.5を実行しています

P.P.S.またgraph_copy = graph[:]graph_copy = list(graph)に置き換えました。同じ振る舞い。あなたが弧を追加すると

+0

なぜあなたはリストのリストを使用していますか?隣接リストは、Pythonで辞書を組み込んで表現できます。 –

+0

試しグラフ.copy? – intrepidhero

+0

私はコードを実行し、このことは起こらなかった。あなたの問題に関する詳細情報を提供してください。 'graph'と' graph_copy'が変更されたときのデバッグ出力があります。 – Tempux

答えて

1

問題はラインに

if choice_flag_1: 
     g_tmp.append(arc) 

である、あなたは内側のリストのシャローコピーを追加しています。そう新しいリストに置き換えてください

if choice_flag_1: 
     g_tmp.append([arc[0],arc[1]]) 
関連する問題