我正在使用蛮力策略来找到我的问题的答案解决方案。我的想法是循环通过3个不同的范围,例如,一个嵌套循环,以10为增量显着减少组合数量。从一个函数传递操作变量以用于另一个函数
然后我在我的第一个函数中给出了三个解决方案,为我的函数重新定义了循环范围参数,这将产生更精确的解决方案。
这是我的代码:
# first broad looping function to zone down to the relevant area of my solution
def t1_solve(cgoal):
max_value = None
nc_f = None
c_f = None
cd_f = None
for i, j, k in [(i,j,k) for i in range(nc_rev.idxmax(),int((cgoal*100)+200),5) for
j in range(c_rev.idxmax(),int((cgoal*100)+200),5) for k in range(cd_rev.idxmax(),
int((cgoal*100)+200),5)]:
if (t1rev(i,j,k) > max_value and t1c(i,j,k) > cgoal):
#storing the optimal value result, and my three solution in nc_f, c_f, cd_f
max_value = t1rev(i,j,k)
nc_f = i
c_f = j
cd_f = k
print max_value
print nc_f, c_f, cd_f
return nc_f
return c_f
return cd_f
# second reduced looping problem to fine-tune my answer
def t1_finetune():
# run the broad looping function
t1_solve(3.61)
# this is where I have trouble with passing my solutions stored in the
# previous function's nc_f, c_f, cd_f
#ERROR OCCURS HERE!!!!!
if nc_f - 20 > 0:
nc_lowerbound = nc_f - 20
else:
nc_lowerbound = 1
if nc_f + 20 < 1499:
nc_upperbound = nc_f + 20
else:
nc_upperbound = 1499
if c_f - 20 > 0:
c_lowerbound = c_f - 20
else:
c_lowerbound = 1
if c_f + 20 < 1499:
c_upperbound = c_f + 20
else:
c_upperbound = 1499
if cd_f - 20 > 0:
cd_lowerbound = cd_f - 20
else:
cd_lowerbound = 1
if cd_f + 20 < 1499:
cd_upperbound = cd_f + 20
else:
cd_upperbound = 1499
for i, j, k in [(i,j,k) for i in range(nc_lowerbound, nc_upperbound) for
j in range(c_lowerbound, c_upperbound) for k in range(cd_lowerbound, cd_upperbound)]:
if (t1rev(i,j,k) > max_value and t1c(i,j,k) > cgoal):
max_value = t1rev(i,j,k)
nc_f = i
c_f = j
cd_f = k
print max_value
print nc_f, c_f, cd_f
return nc_f, c_f, cd_f
t=time.time()
t1_finetune()
print time.time() - t
该错误消息我得到的是:
UnboundLocalError: local variable 'nc_f' referenced before assignment
从本质上讲,我只需要nc_f通过,C_F和cd_f从我t1_solve()在我t1_finetune()。自己运行t1_solve()可以正常工作,并且在t1_finetune()中调用t1_solve()时,它仍然可以运行,直到发生错误发生的代码的其余部分。
我希望这是明确的,请让我知道,如果有什么我可以澄清。
在此先感谢!
@Apero:我第一次在手机上读到这个问题,不知道问题是什么,所以我觉得你的痛苦。 :) – abarnert 2014-10-10 19:15:32