下面是我的代碼,它生成使用的索引,但在某些情況下,會找到一個值,并獲取包含該值的第一個索引,而我需要該值來自的特定索引。
import random
numsLength = random.randint(1,100)
a = [random.randint(0, 400) for i in range(numsLength)]
DP = [[] for i in a] # This will hold bestSeq from i, initially empty
seq = []
mineNum = []
def solveDP(i):
global DP
if i >= len(a):
return []
# If this value is already computed return that value
if len(DP[i]) > 0:
return DP[i]
# Include the current element and go to i 2
arr1 = [a[i]] solveDP(i 2)
# Skip the current element and go to i 1
arr2 = solveDP(i 1)
if sum(arr1) > sum(arr2):
DP[i] = arr1[:] # Copy arr1 into DP[i]
else:
DP[i] = arr2[:] # Copy arr2 into DP[i]
return DP[i]
mines = solveDP(0)
for x in mines: # This loop simply assigns the integers' ordered numbers, in order to track which were used
if a.index(x) 1 not in mineNum:
mineNum.append(a.index(x) 1)
uj5u.com熱心網友回復:
好的,所以我想我明白了。我的解決方案只是在選擇元素時i包含索引。a[i]所需的技巧是sum()用于重新創建您正在計算的值。
import random
numsLength = random.randint(1,100)
print(numsLength)
a = [random.randint(0, 400) for i in range(numsLength)]
DP = [[] for i in a] # This will hold bestSeq from i, initially empty
def solveDP(i):
if i >= len(a):
return []
# If this value is already computed return that value
if DP[i]:
return DP[i]
# Include the current element and go to i 2
arr1 = [(a[i],i)] solveDP(i 2)
# Skip the current element and go to i 1
arr2 = solveDP(i 1)
if sum(i for i, _ in arr1) > sum(i for i, _ in arr2):
DP[i] = arr1[:] # Copy arr1 into DP[i]
else:
DP[i] = arr2[:] # Copy arr2 into DP[i]
return DP[i]
mines = solveDP(0)
mineNum = []
for x,idx in mines:
if idx 1 not in mineNum:
mineNum.append(idx 1)
print(mineNum)
更新:
DPS = [sum(i for i, _ in d) for d in DP]
print(DPS)
print(max(DPS))
但是,您的演算法似乎max將DP
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/504640.html
上一篇:更改多個FASTA檔案中的ID
