我使用蛮力策略来找到问题的答案。我的想法是,我以10为增量遍历3个不同范围(例如嵌套循环)以显着减少组合数量。
然后,我在第一个函数中使用给我的三个解决方案,为我的函数重新定义循环范围参数,这将产生更精确的解决方案。
这是我的代码:
# 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
函数具有三个return
语句,而不是一个。一旦到达第一个,功能就结束了,其他功能就永远不会发生。因此,您需要这样做:
return nc_f, c_f, cd_f
接下来,当您调用t1_solve
它并将这些值返回给您时,您只需忽略结果。您需要将它们存储在某个地方。例如:
nc_f, c_f, cd_f = t1_solve(3.61)
为了直观理解,您在这里要做的是返回三个值而不是一个,并将这三个返回值分配给三个变量。
如果您想知道实际发生的情况:第一个nc_f, c_f, cd_f
创建一个3元素元组并返回该一个元组。然后,后者nc_f, c_f, cd_f =
使用可迭代的分配拆包。请参阅教程节Tuples and Sequences中的介绍。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句