在下面的代码中,我得到了我设置的递归函数的最佳值 现在我想获得帮助构建它的值 - 我的意思是,知道在每个步骤中使用了哪个选择(或者#34;骑"(这是我的决定)),并将其作为字符串返回/阵列/不知。
thestory :我有6次骑行,在每一步中我都需要选择是否继续骑行或切换。每次骑行都有一个有趣的速度,每次我继续它,我想最大限度地享受乐趣。现在我有最佳价值,但不是我继续的游乐设施导致我去了它
功能F是这里的主要焦点。
import math
import numpy as np
#fun rate for each ride,per loop
def funPerRide(rideNum,loopsNum):
if rideNum==1:
return 0
if rideNum==2:
return 100-np.power((4*loopsNum-10),2)
if rideNum==3:
return 50-(1000*np.power(np.e,(-loopsNum/2))/(5*loopsNum+20))
if rideNum==4:
return 4*loopsNum
if rideNum==5:
return 2.5*np.power(loopsNum,2)
if rideNum==6:
return 50*np.power(np.e,(-2*loopsNum+4))
def F(totalTime,timeLeft,rideNum,loopOnCurrRide):
#time of line+operation of ride
totalTimePerRide={1:0,2:40,3:15,4:20,5:23,6:11}
#time of operation of rides
operationTimePerRide={1:0,2:4,3:5,4:8,5:3,6:6}
#unfeasable conditions:
if timeLeft<0:
return -np.inf
if timeLeft+loopOnCurrRide*operationTimePerRide[rideNum]>totalTime:
return -np.inf
if loopOnCurrRide>3:
return -np.inf
#edge condition
if timeLeft == 0:
return 0
#fun if i stay on the ride im on right now
staying = funPerRide(rideNum,loopOnCurrRide+1)-funPerRide(rideNum,loopOnCurrRide)+F(totalTime,timeLeft-operationTimePerRide[rideNum],rideNum,loopOnCurrRide+1)
#calculating fun if i switch to the maximum-fun-ride, that is not the ride im currently at
switching = -1
whichRide=-1
for i in range(1,7):
if i>rideNum:
switchOption = funPerRide(i,loopOnCurrRide)+F(totalTime,timeLeft-4.5-totalTimePerRide[i],i,1)
if switchOption>switching:
switching, whichRide=switchOption,i
#calculating maximum fun between switching and staying
maxval,maxride=max((staying,rideNum),(switching,whichRide))
path.append(maxride)
maxval=float(maxval)
return float(maxval)
path = []
print(F(120,120,1,0),path)
答案 0 :(得分:0)
你的函数F可以返回一对两个值:第一个 - 最佳答案,第二个 - 最佳路径作为索引列表。
def F(totalTime, timeLeft, rideNum, loopOnCurrRide):
# time of line+operation of ride
totalTimePerRide = {1: 0, 2: 40, 3: 15, 4: 20, 5: 23, 6: 11}
# time of operation of rides
operationTimePerRide = {1: 0, 2: 4, 3: 5, 4: 8, 5: 3, 6: 6}
if timeLeft + loopOnCurrRide * operationTimePerRide[rideNum] > totalTime:
return -10, []
if loopOnCurrRide > 3:
return -10, []
if timeLeft == 0:
return 0, []
staying, staying_path = F(totalTime, timeLeft - operationTimePerRide[rideNum], rideNum, loopOnCurrRide + 1)
staying += funPerRide(rideNum, loopOnCurrRide + 1) - funPerRide(rideNum, loopOnCurrRide)
staying_path = [-1] + staying_path
switching = -1
switching_path = []
for i in range(1, 7):
if i > rideNum:
switchOption, switchOption_path = F(totalTime, timeLeft - 4.5 - totalTimePerRide[i], i, 1)
switchOption += funPerRide(i, loopOnCurrRide)
if switchOption > switching:
switching = switchOption
switching_path = [i] + switchOption_path
return max((staying, staying_path), (switching, switching_path))
answer, path = F(120, 120, 1, 0)