我正在使用蠻力策略來找到我的問題的答案解決方案。我的想法是循環通過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