這個想法是爲每個數字添加下一個連續數字以嘗試達到目標值。如果對於每個起始值(對於我...)如果添加下一個連續數字超過目標,那麼我已經失敗並轉移到下一個。將列表中的連續值添加到目標值
我得到一些值滑倒和一些重複。
如果目標有意匹配它的工作正常的列表;我注意到有13個怪異的行爲。
def addToTarget (mylist, target):
solutions_list = []
for i in range(0,len(mylist)):
#set base values
total = mylist[i]
counter = i
solutions = []
solutions.append(total)
if total == target:
solutions_list.append(solutions) # first value matches immediately
elif total > target:
solutions_list.append([counter-1, "first value already too high"])
elif counter == (len(mylist)):
solutions_list.append("caught as final value ")
while total < target and counter < (len(mylist)-1):
counter +=1
value = mylist[counter]
total += value
solutions.append(value)
if total == target:
solutions_list.append([counter, solutions])
elif total > target:
solutions_list.append([counter-1, "total > target during"])
elif counter == (len(mylist)-1):
solutions_list.append([counter-1, "total < target - came to end of list "])
else : solutions_list.append([counter-1, "not sure but certian values seem to slip through"])
return solutions_list
mylist = [5, 5, 3, 10, 2, 8, 10]
solutions_list = []
test = answer(mylist, 13)
for i in test : print(i)
可以添加你的預期輸出? –
根據所列的名單和13我的目標期望答案= [[5,5,3],失敗,[3,10],失敗,失敗,失敗,失敗] – Jup
我已經添加了計數器號碼到輸出看到,在這種情況下,在索引2處有多個條目,在索引0和1處沒有條目,在索引5處有兩個條目。我嘗試跟蹤這些值(我在火車上也有幾個啤酒...但是我有點笨拙,我敢肯定它有些愚蠢和簡單(又名非常討厭) – Jup