リスト内で最も長くなっている連続したサブシーケンスを検索しようとしています。サブシーケンスが連続的に増加しています
例:それは長い[1,2,3]
以上と[1,4,5,6,9]
だけだとして[1,2,3,0,2,3,5,6,7,1,4,5,6,9]
出力は[0,2,3,5,6,7]
をする必要があります:私は、リストを持っている場合より小さい各シーケンスの長さを計算する。しかし、私がしなければならないのは、長さではなく最長のサブシーケンスを出力することです。それを行うことができないような奇妙な理由のために(私は論理的なエラーを出し続けます)。
これは私のコードです。これは私が実装しようとした方法の1つで、私が直面している問題は、をarr2
に追加するときです。私はこれを修正するのを手伝ってください。これに代わるより効率的な代替アルゴリズムを提案してください。
arr = [1,2,3,0,2,3,5,6,7,1,4,5,6,9] #original list
arr2 = [] #empty list (2 dimension)
counter = 1
temp = [] #temporary list
for x,y in enumerate(arr):
if(x == 0):
temp.append(y) #append first value to temp
else:
if(arr[x] > arr[x-1]): #if value of x is greater than previous one:
counter += 1 #increase counter if condition met
temp.append(y) #append list value to temp
else: #if value of x is not greater than previous one:
print(temp)
arr2.append(temp) #append entire temp list to arr2
temp[:] = [] #clear the temp list
temp.append(y) #append the new lowest value to temp
counter = 1 #reset counter
print(arr2)
ヘルプメイトに感謝します。しかし、ちょっと修正するだけですが、ループの外側でarr2に最後のサブシーケンスを追加する必要がありますが、最後のelseステートメント内にリストのコピーを作成する必要があります。arr2.append(temp [:] ).. 再度、感謝します! –