简体   繁体   中英

infinite loop in python?

I've been working on the Knapsack problem implementation, but I could not implement it right the code just keeps going into this infinite loop of while(true)
here's the code:

class KSBB:
    global x
    global y
    x=[]
    y=[]
    global sp
    sp=0
    global cw
    global cp
    global nw
    global np
    cw,cp,nw,np=0,0,0,0
    global k
    k=0
    global pi
    pi=0
def __init__(self,a,b,c):
    self.weights=a
    self.values=b
    self.c=c
    x=len(self.weights)
    y=len(self.weights)

Bound method:

def bound(self):
    global cp
    found=False
    bv=0
    n=len(self.weights)
    np=cp
    nw=cw
    pi=k
    while(pi < n and ~found):
        if(nw+self.weights[pi] <= self.c):
            nw+=self.weights[pi]
            np+=self.values[pi]
            y.append(1)
        else:
            bv=np+((self.c-nw)*(self.values[pi]/self.weights[pi]))
            found=True
            #y.append(0)
        pi+=1
    if found:
        pi-=1
        return bv
    else:
        return np

Branching Method:

def Knapsack(self):
    n=len(self.weights)
    while True:
        global sp
        while (self.bound() <= sp):
            while(k !=0 and y[k] !=1):
                k-=1 
            if (K==0):return
            y[k]=0
            cw-=self.weights[k]
            cp-=self.values[k]
        cw=nw
        cp=np
        k=pi
        print k
        if (k==n):              
            sp=cp
            x=y
            k=n-1
        else:
            y[k]=0

Output Method:

def output(self):return sp
if (K==0)

should probably be

if (k==0)

Just a typo...

It is easy to localize this problem - you know where you want to terminate your loop and the only thing which can go wrong is your if statement. Spotting such things is easy and one of the most basic things to master in programming. You need to learn debugging as soon as your programs start to be longer than 5 lines.

~found is a bitwise complement. I think you mean not found !

>>> ~False
-1             # True
>>> ~True
-2             # also True!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM