1

我已经使用这个程序有一段时间了,坚持下去似乎很乏味,但我正在运行我的代码以pylint进行锻炼,我收到错误R0912: 69,0:process_ancestors: Too many branches (7/6) . 我想知道是否有人能够帮助我缩小这个功能,因为它对我来说似乎是最简单的形式......

def process_ancestors(relation_dict, name):
    '''Figures out who the ancestors are'''
    output_str = ''
    name_found = search_name(relation_dict, name)
    if not name_found: 
            output_str = "Unknown person"      
    else: 
        ancestor_list = []
        person = name
        while True: 
            person = find_parent(relation_dict, person)
            if person == None: 
                break
            else: 
                ancestor_list.append(person)
        if ancestor_list: 
            output_str = ", ".join(ancestor_list)
        else: 
            output_str = "No known ancestors"            

    return output_str

为你的帮助干杯!

4

3 回答 3

2

早点返回,这样你需要的else:分支要少得多:

def process_ancestors(relation_dict, name):
    '''Figures out who the ancestors are'''
    name_found = search_name(relation_dict, name)
    if not name_found: 
        return "Unknown person"      

    ancestor_list = []
    person = find_parent(relation_dict, name)
    while person is not None:
        ancestor_list.append(person)
        person = find_parent(relation_dict, person)

    if not ancestor_list: 
        return "No known ancestors"            
    return ", ".join(ancestor_list)

我还删除了测试是否在循环中的需要personNone删除while了另一个分支。

于 2013-05-22T09:44:15.973 回答
2

变化是:

  1. 返回imeidelty(删除了两个分支)
  2. 通过将第一次迭代设置为之前发生来更改 while 循环,从而无需检查None循环内部

导致:

def process_ancestors(relation_dict, name):
    '''Figures out who the ancestors are'''
    name_found = search_name(relation_dict, name)
    if not name_found: 
            return "Unknown person"      
    ancestor_list = []
    person = name
    person = find_parent(relation_dict, person)
    while person is not None: 
        ancestor_list.append(person)
        person = find_parent(relation_dict, person)
    return ", ".join(ancestor_list) if ancestor_list else "No known ancestors"
于 2013-05-22T09:45:22.017 回答
1

不确定它是否更短,但至少对我来说更清楚:

def process_ancestors(relation_dict, name):
    '''Figures out who the ancestors are'''
    if not search_name(relation_dict, name):
        return "Unknown person"
    else:
        ancestor_list = list(ancestors(relation_dict, name))
        if not ancestor_list:
            return "Unknown parent"
        else:
            return ", ".join(ancestor_list)

def ancestors(relation_dict, person):
    '''A list of ancestors (excluding first person)'''
    while person:
        person = find_parent(relation_dict, person)
        if person: yield person
于 2013-05-22T09:50:25.357 回答