正如@NullUserException 所说,一棵树(或类似的东西)是一个不错的选择。我发布的答案与您为这个问题选择的答案完全不同。
您可以定义一个 Person 对象,该对象知道其名称并跟踪其父对象。父对象不是名字而是另一个 Person 对象!(有点像链表)。然后,您可以将人员集合保留为单个列表。
在解析文件时,您不断将人员添加到列表中,同时使用正确的对象更新他们的子/父属性。
以后给任何人,打印属性找关系就行了
以下是一个可能的实现(在 Python-2.6 上)。在这种情况下,文本文件只包含关系。稍后使用交互式输入触发查询
class Person(object):
"""Information about a single name"""
def __init__(self,name):
self.name = name
self.parent = None
self.children = []
def search_people(people,name):
"""Searches for a name in known people and returns the corresponding Person object or None if not found"""
try:
return filter(lambda y: y.name == name,people)[0]
except IndexError:
return None
def search_add_and_return(people,name):
"""Search for a name in list of people. If not found add to people. Return the Person object in either case"""
old_name = search_people(people,name)
if old_name is None:
#First time entry for the name
old_name = Person(name)
people.append(old_name)
return old_name
def read_file(file_name,people):
fp = open(file_name,'r')
while True:
l = fp.readline()
l.strip('\n').strip()
if not l:
break
names = l.split(':')
mother = names[0].strip()
children = [x.strip() for x in names[1].split(',')]
old_mother = search_add_and_return(people,mother)
#Now get the children objects
child_objects = []
for child in children:
old_child = search_add_and_return(people,child)
child_objects.append(old_child)
#All children have been gathered. Link them up
#Set parent in child and add child to parent's 'children'
old_mother.children.extend(child_objects)
for c in child_objects:
c.parent = old_mother
fp.close()
def main():
file_name = 'try.txt'
people = []
read_file(file_name,people)
#Now lets define the language and start a loop
while True:
command = raw_input("Enter your command or 0 to quit\n")
if command == '0':
break
coms = command.split()
if len(coms) < 2:
print "Wrong Command"
continue
action = coms[0]
param = coms[1]
if action == "mother":
person = search_people(people,param)
if person == None:
print "person not found"
continue
else:
if person.parent is None:
print "mother not known"
else:
print person.parent.name
elif action == "ancestors":
person = search_people(people,param)
if person == None:
print "person not found"
continue
else:
ancestor_list = []
#Need to keep looking up parent till we don't reach a dead end
#And collect names of each ancestor
while True:
person = person.parent
if person is None:
break
ancestor_list.append(person.name)
if ancestor_list:
print ",".join(ancestor_list)
else:
print "No known ancestors"
if __name__ == '__main__':
main()
编辑
由于您希望保持简单,因此这是一种使用字典(单个字典)来做您想做的事情的方法
基本思路如下。您解析文件以形成一个字典,其中键是Mother
,值是list of children
。所以当你的示例文件被解析时,你会得到一个像
relation_dict = {'Charlotte': ['Tim'], 'Sue': ['Chad', 'Brenda', 'Harris'], 'Alice': ['John', 'Dick', 'Harry'], 'Brenda': ['Freddy', 'Alice']}
要查找父级,只需搜索名称是否在字典值中,如果找到则返回键。如果没有找到妈妈,返回 None
mother = None
for k,v in relation_dict.items():
if name in v:
mother = k
break
return mother
如果你想找到所有的祖先,你只需要重复这个过程,直到返回 None
ancestor_list = []
person = name
while True:
person = find_parent(relation_dict,person)
if person == None:
#Top of the ancestor chain found
break
else:
ancestor_list.append(person)
这是 Python-2.6 中的一个实现。它假定您的文本文件的结构首先是所有关系,然后是空行,然后是所有命令。
def read_file(file_name):
fp = open(file_name,'r')
relations = []
commands = []
reading_relations = True
for l in fp:
l = l.strip('\n')
if not l:
reading_relations = False
continue
if reading_relations:
relations.append(l.strip())
else:
commands.append(l.strip())
fp.close()
return relations,commands
def form_relation_dict(relations):
relation_dict = {}
for l in relations:
names = l.split(':')
mother = names[0].strip()
children = [x.strip() for x in names[1].split(',')]
existing_children = relation_dict.get(mother,[])
existing_children.extend(children)
relation_dict[mother] = existing_children
return relation_dict
def search_name(relation_dict,name):
#Returns True if name occurs anywhere in relation_dict
#Else return False
for k,v in relation_dict.items():
if name ==k or name in v:
return True
return False
def find_parent(relation_dict,param):
#Finds the parent of 'param' in relation_dict
#Returns None if no mother found
#Returns mother name otherwise
mother = None
for k,v in relation_dict.items():
if param in v:
mother = k
break
return mother
def process_commands(commands,relation_dict):
output = []
for c in commands:
coms = c.split()
if len(coms) < 2:
output.append("Invalid Command")
continue
action = coms[0]
param = coms[1]
if action == "mother":
name_found = search_name(relation_dict,param)
if not name_found:
output.append("person not found")
continue
else:
person = find_parent(relation_dict,param)
if person is None:
output.append("mother not known")
else:
output.append("mother - %s" %(person))
elif action == "ancestors":
name_found = search_name(relation_dict,param)
if not name_found:
output.append("person not found")
continue
else:
#Loop through to find the mother till dead - end (None) is not reached
ancestor_list = []
person = param
while True:
person = find_parent(relation_dict,person)
if person == None:
#Top of the ancestor found
break
else:
ancestor_list.append(person)
if ancestor_list:
output.append(",".join(ancestor_list))
else:
output.append("No known ancestors")
return output
def main():
file_name = 'try.txt'
relations,commands = read_file(file_name)
#Process Relqations to form a dictionary of the type {parent: [child1,child2,...]}
relation_dict = form_relation_dict(relations)
print relation_dict
#Now process commands in the file
output = process_commands(commands,relation_dict)
print '\n'.join(output)
if __name__ == '__main__':
main()
您的样本输入的输出是
mother not known
Alice,Brenda,Sue
person not found
No known ancestors
编辑2
如果您真的想将其进一步拆分为功能,process_commands
请查看以下内容
def process_mother(relation_dict,name):
#Processes the mother command
#Returns the ouput string
output_str = ''
name_found = search_name(relation_dict,name)
if not name_found:
output_str = "person not found"
else:
person = find_parent(relation_dict,name)
if person is None:
output_str = "mother not known"
else:
output_str = "mother - %s" %(person)
return output_str
def process_ancestors(relation_dict,name):
output_str = ''
name_found = search_name(relation_dict,name)
if not name_found:
output_str = "person not found"
else:
#Loop through to find the mother till dead - end (None) is not reached
ancestor_list = []
person = name
while True:
person = find_parent(relation_dict,person)
if person == None:
#Top of the ancestor found
break
else:
ancestor_list.append(person)
if ancestor_list:
output_str = ",".join(ancestor_list)
else:
output_str = "No known ancestors"
return output_str
def process_commands(commands,relation_dict):
output = []
for c in commands:
coms = c.split()
if len(coms) < 2:
output.append("Invalid Command")
continue
action = coms[0]
param = coms[1]
if action == "mother":
new_output = process_mother(relation_dict,param)
elif action == "ancestors":
new_output = process_ancestors(relation_dict,param)
if new_output:
output.append(new_output)
return output