python中超过10000个元素的递归

2024-09-24 16:35:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,想用branch-and-bound来解决背包问题,当我增加递归限制时,我的代码可以很好地运行1000个元素,但是不管我设置多高的递归限制,我的代码都能处理10000个元素

为什么这段代码跨越递归限制,Mcount值只显示10000,这意味着它在递归堆栈中存储的数据不超过10000个节点。我想我错过了一些东西,但不知道是什么。在

def rep(i):
    global taken
    global Btaken
    global Tvalue
    global Tweight  
    global Bestimate
    global Bvalue
    global count
    global Mcount   
    count+=1    
    Tweight -= items[i].weight
    if Tweight>=0 :
        taken[items[i].index-1] = 1 
        Tvalue += items[i].value    
        if i < len(items)-1:
            rep(i+1)
        else :
            Btaken=taken*1
            Bvalue = Tvalue     
        Tvalue -= items[i].value                
        taken[items[i].index-1]=0   
    Tweight += items[i].weight      
    Bestimate = best(i+1,Tweight)
    if Bestimate+Tvalue > Bvalue :  
        if i < len(items)-1:
            rep(i+1)
        else :
            Btaken=taken*1
            Bvalue = Tvalue 
    if Mcount<count :
        Mcount=count    
    count-=1

Tags: 代码元素ifcountitemsglobaltakenweight