而真算法迭代Python

时间:2014-01-13 09:49:57

标签: python while-loop conditional-statements cycle

我有这段代码:

split_at = q[:,3].searchsorted([1,random.randrange(LB,UB-I)])
D = numpy.split(q, split_at) 
T=D[1]
TF=D[2]
T2=copy(TF)
T2[:,3]=T2[:,3]+I
u=random.sample(T[:],1)
v=random.sample(T2[:],1)
u=array(u)
v=array(v)
d=v[0,0]-u[0,0]+T[-1,3]

我希望if d< = 1000:

x=numpy.where(v==T2)[0][0]
y=numpy.where(u==T)[0][0]
l=np.copy(T[y])
T[y],T2[x]=T2[x],T[y]
T2[x],l=l,T2[x]
E=np.copy(T)
E2=np.copy(T2)
E[:,3]=np.cumsum(E[:,0])
E2[:,3]=np.cumsum(E2[:,0])+I
f2=sum(E[:,1]*E[:,3])+sum(E2[:,1]*E2[:,3])

而不是那个if d>1000我想要重新计算代码的第一部分并验证if d<=1000并反复验证,直到满足条件。

2 个答案:

答案 0 :(得分:0)

从以下开始:

d = 1000000
while d > 1000:
    split_at = q[:,3].searchsorted([1,random.randrange(LB,UB-I)])
    D = numpy.split(q, split_at) 
    T=D[1]
    TF=D[2]
    T2=copy(TF)
    T2[:,3]=T2[:,3]+I
    u=random.sample(T[:],1)
    v=random.sample(T2[:],1)
    u=array(u)
    v=array(v)
    d=v[0,0]-u[0,0]+T[-1,3]
x=numpy.where(v==T2)[0][0]
y=numpy.where(u==T)[0][0]
l=np.copy(T[y])
T[y],T2[x]=T2[x],T[y]
T2[x],l=l,T2[x]
E=np.copy(T)
E2=np.copy(T2)
E[:,3]=np.cumsum(E[:,0])
E2[:,3]=np.cumsum(E2[:,0])+I
f2=sum(E[:,1]*E[:,3])+sum(E2[:,1]*E2[:,3])

答案 1 :(得分:0)

为什么不将代码安排到以下函数中:

def func1(): # add your arguments to param list
   split_at = q[:,3].searchsorted([1,random.randrange(LB,UB-I)])
   # some code 
   d=v[0,0]-u[0,0]+T[-1,3]
   return d,T,T2

def func2(T,T2):
   x=numpy.where(v==T2)[0][0]
   # more code       

并做一些像:

d = 10000
while  d > 1000:
   d,T,T2 = func1()
else:
   func2(T,T2)