- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我目前有一个程序可以读取一个文本文件并根据里面的输入回答一组查询。它有助于弄清楚被问及的 child 的母亲是谁。我现在更进一步,重新处理提供的这些输出以显示完整的家谱。
这是包含左侧 parent 和右侧 child 的文本文件。下面是被询问的查询,后面是输出。
Sue: Chad, Brenda, Harris
Charlotte: Tim
Brenda: Freddy, Alice
Alice: John, Dick, Harry
mother Sue
ancestors Harry
ancestors Bernard
ancestors Charlotte
>>> Mother not known
>>> Alice, Brenda, Sue
>>> Unknown Person
>>> No known ancestors
该程序能够计算出母亲是谁(感谢 Kampu 的帮助),但我现在正试图了解如何获取此值并可能将其附加到一个新的无限循环查找任何可能的祖 parent 的列表或字典。
def lookup_ancestor(child):
ancestor = REVERSE_MAP.get(child)
if ancestor:
ANCESTOR_LIST_ADD.append(ancestor)
if ancestor not in LINES[0:]:
print("Unknown person")
else:
print("No known ancestors")
这是我目前所拥有的,其中 REVERSE_MAP
将每个子项映射到字典中的父项。然后,我将 parent 放入一个新列表中,我计划再次运行该列表以确定他们的 parent 是谁。然而,我被困在这一点上,因为我无法找到一种优雅的方式来执行整个过程,而无需创建三个新列表来保持循环。目前的设置方式,我假设我需要通过 for
循环附加它们或只是 split()
之后的值以保留所有彼此的值(value)观。理想情况下,我想学习如何循环这个过程并找出每个问题的祖先是谁。
我觉得我似乎已经掌握了它应该看起来如何,但是我对 Python 的了解使我的试错法无法节省时间。
如有任何帮助,我们将不胜感激!
编辑: 链接 - http://pastebin.com/vMpT1GvX
编辑 2:
def process_commands(commands, relation_dict):
'''Processes the output'''
output = []
for c in commands:
coms = c.split()
if len(coms) < 2:
output.append("Invalid Command")
continue
action = coms[0]
param = coms[1]
def mother_lookup(action, param, relation_dict):
output_a = []
if action == "mother":
name_found = search_name(relation_dict, param)
if not name_found:
output_a.append("Unknown person")
else:
person = find_parent(relation_dict, param)
if person is None:
output_a.append("Mother not known")
else:
output_a.append(person)
return output_a
def ancestor_lookup(action, param, relation_dict):
output_b = []
if action == "ancestors":
name_found = search_name(relation_dict, param)
if not name_found:
output_b.append("Unknown person")
else:
ancestor_list = []
person = param
while True:
person = find_parent(relation_dict, person)
if person == None:
break
else:
ancestor_list.append(person)
if ancestor_list:
output_b.append(", ".join(ancestor_list))
else:
output_b.append("No known ancestors")
return output_b
def main():
'''Definining the file and outputting it'''
file_name = 'relationships.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)
#Now process commands in the file
action = process_commands(commands, relation_dict)
param = process_commands(commands, relation_dict)
output_b = ancestor_lookup(action, param, relation_dict)
output_a = mother_lookup(action, param, relation_dict)
print('\n'.join(output_a))
print ('\n'.join(output_b))
if __name__ == '__main__':
main()
最佳答案
正如@NullUserException 所说,一棵树(或类似的东西)是一个不错的选择。我发布的答案与您为这个问题选择的答案完全不同。
您可以定义一个 Person 对象,该对象知道自己的名字并跟踪其父对象是谁。 parent 不是一个名字,而是另一个 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
如果你想找到所有的祖先,你只需要重复这个过程直到没有返回
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
EDIT2
如果你真的想把它进一步拆分成函数,下面是 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
关于python - 循环字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16673445/
我是 PHP 新手。我一直在脚本中使用 for 循环、while 循环、foreach 循环。我想知道 哪个性能更好? 选择循环的标准是什么? 当我们在另一个循环中循环时应该使用哪个? 我一直想知道要
我在高中的编程课上,我的作业是制作一个基本的小计和顶级计算器,但我在一家餐馆工作,所以制作一个只能让你在一种食物中读到。因此,我尝试让它能够接收多种食品并将它们添加到一个价格变量中。抱歉,如果某些代码
这是我正在学习的一本教科书。 var ingredients = ["eggs", "milk", "flour", "sugar", "baking soda", "baking powder",
我正在从字符串中提取数字并将其传递给函数。我想给它加 1,然后返回字符串,同时保留前导零。我可以使用 while 循环来完成此操作,但不能使用 for 循环。 for 循环只是跳过零。 var add
编辑:我已经在程序的输出中进行了编辑。 该程序要求估计给定值 mu。用户给出一个值 mu,同时还提供了四个不等于 1 的不同数字(称为 w、x、y、z)。然后,程序尝试使用 de Jaeger 公式找
我正在编写一个算法,该算法对一个整数数组从末尾到开头执行一个大循环,其中包含一个 if 条件。第一次条件为假时,循环可以终止。 因此,对于 for 循环,如果条件为假,它会继续迭代并进行简单的变量更改
现在我已经习惯了在内存非常有限的情况下进行编程,但我没有答案的一个问题是:哪个内存效率更高;- for(;;) 或 while() ?还是它们可以平等互换?如果有的话,还要对效率问题发表评论! 最佳答
这个问题已经有答案了: How do I compare strings in Java? (23 个回答) 已关闭 8 年前。 我正在尝试创建一个小程序,我可以在其中读取该程序的单词。如果单词有 6
这个问题在这里已经有了答案: python : list index out of range error while iteratively popping elements (12 个答案) 关
我正在尝试向用户请求 4 到 10 之间的整数。如果他们回答超出该范围,它将进入循环。当用户第一次正确输入数字时,它不会中断并继续执行 else 语句。如果用户在 else 语句中正确输入数字,它将正
我尝试创建一个带有嵌套 foreach 循环的列表。第一个循环是循环一些数字,第二个循环是循环日期。我想给一个日期写一个数字。所以还有另一个功能来检查它。但结果是数字多次写入日期。 Out 是这样的:
我想要做的事情是使用循环创建一个数组,然后在另一个类中调用该数组,这不会做,也可能永远不会做。解决这个问题最好的方法是什么?我已经寻找了所有解决方案,但它们无法编译。感谢您的帮助。 import ja
我尝试创建一个带有嵌套 foreach 循环的列表。第一个循环是循环一些数字,第二个循环是循环日期。我想给一个日期写一个数字。所以还有另一个功能来检查它。但结果是数字多次写入日期。 Out 是这样的:
我正在模拟一家快餐店三个多小时。这三个小时分为 18 个间隔,每个间隔 600 秒。每个间隔都会输出有关这 600 秒内发生的情况的统计信息。 我原来的结构是这样的: int i; for (i=0;
这个问题已经有答案了: IE8 for...in enumerator (3 个回答) How do I check if an object has a specific property in J
哪个对性能更好?这可能与其他编程语言不一致,所以如果它们不同,或者如果你能用你对特定语言的知识回答我的问题,请解释。 我将使用 c++ 作为示例,但我想知道它在 java、c 或任何其他主流语言中的工
这个问题不太可能帮助任何 future 的访问者;它只与一个小的地理区域、一个特定的时间点或一个非常狭窄的情况有关,这些情况并不普遍适用于互联网的全局受众。为了帮助使这个问题更广泛地适用,visit
我是 C 编程和编写代码的新手,以确定 M 测试用例的质因数分解。如果我一次只扫描一次,该功能本身就可以工作,但是当我尝试执行 M 次时却惨遭失败。 我不知道为什么 scanf() 循环有问题。 in
这个问题已经有答案了: JavaScript by reference vs. by value [duplicate] (4 个回答) 已关闭 3 年前。 我在使用 TSlint 时遇到问题,并且理
我尝试在下面的代码中添加 foreach 或 for 循环,以便为 Charts.js 创建多个数据集。这将允许我在此折线图上创建多条线。 我有一个 PHP 对象,我可以对其进行编码以稍后填充变量,但
我是一名优秀的程序员,十分优秀!