如何使用var来中断所有递归调用?

时间:2013-11-22 19:46:42

标签: python recursion

所以我正在编写一个递归函数,找到2 dna链的最佳分数,我的问题是我有2个vars我想保存和使用(函数之外的变量,就像java上的变量vars):

1)如果找到最佳解决方案,我不想继续搜索 2)并保留一个包含我迄今为止最好的解决方案的var,所以如果当前得分无论如何都不能超过它,我想停止搜索。

代码:

def main_fun(str1,str2)
    best_so_far = None
    best_score_possible = len(str)* match
    score_fund = False
    def recursive(index, index2, score)
        if score_fund is True:
            return
        if score + chances < best_so_far:
            return
        if score == best_score_possible:
           score_fund = True
        # rest of code and other calls

这不是真正的代码,但它正是我想要做的,任何想法? 谢谢

真实(不完整)代码:

def best_helper(dna_1, dna_2, index_1, index_2, score):
    best_future = score + calculate_best_future(index_1, index_2)
    if best_future < worst_score_possible:# or best_future < best_so_far:
        return worst_score_possible, dna_1, dna_2

    #returns when done and complete rest with dash
    if index_1 == len(first_dna) and index_2 == len(second_dna):
        if len(dna_1) > len(dna_2):
            dna_2 += '-' * (len(dna_1) - len(dna_2))
            score += dash * (len(dna_1) - len(dna_2))
        elif len(dna_2) > len(dna_1):
            dna_1 += '-' * (len(dna_2) - len(dna_1))
            score += dash * (len(dna_2) - len(dna_1))
        if score == best_score_possible:
            strand_found = True
        if score > best_so_far:
            best_so_far = score
        return score, dna_1, dna_2

2 个答案:

答案 0 :(得分:0)

提出异常

def main_fun(str1,str2)
    best_so_far = None
    best_score_possible = len(str)* match
    score_fund = False
    def recursive(index, index2, score)
        if score_fund is True:
            return
        if score + chances < best_so_far:
            return
        if score == best_score_possible:
           raise Exception("Best Possible Score Found!")
    try:
       recursive(0,1,0)
    except Exception as msg:
       if str(msg) == "Best Possible Score Found!":
             print "WIN!!!"
       else:
           raise

答案 1 :(得分:0)

您只需返回一个额外的Boolean value,表示是否找到了解决方案。

如果该值设置为True,则只返回相同的值,直到整个堆栈清空为止。如果False,您应该继续检查其他可能的情况。

示例:

def process_tree( best_score, node=root ):

    if not node:
        return ["NaN",False]

    node_score = node.evaluate_score()
    if node_score == best_score:
        return [best_score, True]

    score_list = []
    score_list.append(node_score)
    for child in node.children:

        child_score = process_tree(best_score,child)
        if child_score[1]:
            return child_score
        else:
            score_list.append(child_score[0])

    #when no score is equal to the best score
    return [max(score_list),False]

P.S。 (编辑):这个例子非常重要。我希望它能让事情变得清晰 -