我在面试中解决了问题。他们提出了一个json对象:
putchar(A)
需要组织结构的格式输出,如:
{
"UserName": "Tom Las",
"title": "Director"
},
{
"UserName": "Mike Sea",
"title": "senior manager"
},
{
"UserName": "Jojo Lee",
"title": "manager",
"direct Report": "Mike Sea"
},
{
"UserName": "Luke Shi",
"title": "manager",
"direct Report": "Mike Sea"
},
{
"UserName": "Bob Aeo",
"title": "engineer",
"direct Report": "Luke Shi"
},
{
"UserName": "Zobu hu",
"title": "engineer",
"direct Report": "Tom Las"
}
这是我的解决方案。我使用两个字典来跟踪领导者和团队成员信息并使用" " * n缩进子团队中的团队成员。我觉得下面的代码是笨拙的,并且不能灵活地显示更多级别的子团队,例如,如果" Bob Aeo"他下面也有团队成员。在这种情况下,我应该考虑不同的数据结构而不是字典吗?谢谢!
Mike Sea - senior manager
Jojo Lee
Luke Shi
Bob Aeo
Tom Las - Director
Zobu hu
答案 0 :(得分:1)
建立一个树...我将“直接报告”更改为“经理”,因为我认为重点是在MemberInfo
对象中命名该人的经理。管理器的反向链接是直接报告列表,因此我在下面的示例中设置了该列表。我开始索引列表,添加一个"direct reports"
列表,然后填写该列表。然后,这只是一个递归例程的问题,打印和输入后跟任何直接报告。代码没有假设组织是多么臃肿,但是假设列表中没有循环......我曾经在自己的工作中向自己报告并且对各种软件造成了严重破坏。有趣的是,我当时正致力于管理Active Directory Manager
和directReports
字段的代码。
MemberInfo = [
{
"UserName": "Tom Las",
"title": "Director"
},
{
"UserName": "Mike Sea",
"title": "senior manager"
},
{
"UserName": "Jojo Lee",
"title": "manager",
"Manager": "Mike Sea"
},
{
"UserName": "Luke Shi",
"title": "manager",
"Manager": "Mike Sea"
},
{
"UserName": "Bob Aeo",
"title": "engineer",
"Manager": "Luke Shi"
},
{
"UserName": "Zobu hu",
"title": "engineer",
"Manager": "Tom Las"
}
]
def crawl_ranks(name, indent=''):
"""Prints member and direct report names recursively"""
member = member_index[name]
print('{}{}'.format(indent, member['UserName']))
for name in sorted(member.get('direct reports', [])):
crawl_ranks(name, indent=indent + ' ')
# index by name for easy lookup
member_index = {member['UserName']:member for member in MemberInfo}
# add direct reports list to member info
for member in MemberInfo:
member['direct reports'] = []
# add dummy index entry for bossless persons
member_index[None] = {'direct reports':[]}
# add member name to boss's direct reports list
for member in MemberInfo:
member_index[member.get('Manager')]['direct reports'].append(member['UserName'])
# print, starting with top-level managers
for name in sorted(member_index[None]['direct reports']):
crawl_ranks(name)