减肥功能

时间:2013-05-22 09:39:16

标签: python python-3.x

我已经有一段时间了这个程序,看起来很乏味但是为了练习我正在针对pylint运行我的代码并且我得到错误 R0912:69,0 :process_ancestors:分支太多(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

为你的帮助干杯!

3 个答案:

答案 0 :(得分: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)

我还删除了在person循环中测试Nonewhile,删除另一个分支的需要。

答案 1 :(得分:2)

变化是:

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

    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"
    

答案 2 :(得分: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