から子孫と先祖を探す:Pythonの - 私は、次の形式でソートされていない親子階層のファイル(タブ区切り)はソートされていない階層のファイル
City1 Area1
City1 Area2
Continent1 Country1
Continent2 Country2
Continent3 Country3
Continent4 Country4
Continents Continent1
Continents Continent2
Continents Continent3
Continents Continent4
Country1 State1
Country2 State2
Country3 State3
Earth Continents
State1 City1
State1 City1.1
State2 City2
を私の目標は、すべての「子孫」を見つけることですし、与えられたメンバーの "祖先"。ここで
は、私がこれまで行うコード化されたものである:予想通り
import sys, re
with open("input.txt", "r") as my_in:
collections={}
for line in my_in:
parent, child=line.rstrip('\r\n').split('\t')
collections.setdefault(parent, []).append(child)
print (collections)
'''
{'Continent4': ['Country4'], 'Continent2': ['Country2'],
'Continents': ['Continent1', 'Continent2', 'Continent3', 'Continent4'],
'Continent1': ['Country1'], 'Country2': ['State2'],
'Country3': ['State3'], 'State1': ['City1', 'City1.1'],
'Country1': ['State1'], 'State2': ['City2'],
'Earth': ['Continents'], 'City1': ['Area1', 'Area2'], 'Continent3': ['Country3']}
'''
def find_descendants(parent, collections):
descendants = []
for descendant in collections[parent]:
if descendant in collections:
descendants = descendants + find_descendants(descendant, collections)
else:
descendants.append(descendant)
return descendants
# Get descendants of "Continent1":
lis=find_descendants("Continent1", collections)
print (lis) # It shows ['Area1', 'Area2', 'City1.1']
# Actually it should show ['Country1', 'State1', 'City1', 'Area1', 'Area2', 'City1.1']
def find_ancestors(child, collections):
# pseudo code
# link child to its parent and parent to its parent until no more parents are found
pass
# lis=find_ancestors("City1.1", collections)
# should show ['Earth', 'Continents', 'Continent1', 'Country1', 'State1']
機能find_descendantsが機能していません。 find_ancestors関数に関しては、私は擬似コードを知っていますが、Pythonで表現することはできません。
助けてください。
コレクションの子孫である場合、 'descendants'に' descendant'を追加するのを忘れます。 – RaphaMex
R. Sabanありがとうございます。私はその変更と機能を作ったfind_descendantsは動作するように見えます。しかし、私はfind_ancestors関数を機能させることができません。 –