2013-11-22 28 views
1

所以我写了一个递归函数,找到最佳得分2 dna链,我的问题是,我有2个变种我想保存和使用(功能以外的变量,如提起的变量在java上):如何使用var从所有递归调用中中断?

1 )如果找到最佳解决方案,我不想继续搜索 2)并保留一个包含我迄今为止最好的解决方案的变种,所以如果当前的分数无法胜过它,我想停止搜索。

代码:

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 

回答

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. (编辑):这个例子是相当不平凡的。我希望它能说清楚 - er

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 
+0

的问题是,我不能改变或从外部函数read瓦尔,它说:“没有解决refernce迄今为止最好的 – user2918984

+0

?什么?相信你能... –

+0

pyCharm说我不能:-( – user2918984