我仍在學習更多有關編程的知識,并且我的代碼有問題。
我有一個陣列
data = [5,4,4,4,4,3,3,8] 預期結果應該是 P,n,n,n,n,n,v,p。但我得到這個 p,n,n,n,p,n,n,p
#data = [2,1,4,5,5,5,4] 預期結果 p,v,n,n,n,p,v (我的代碼適用于此。但代碼必須能夠解決這兩個問題)
我想將它們分配給 Peak(P) 和 Valley(V)。
其中峰值是高數,谷是低數。
.
def get_Ps_values(data):
dt=[]
details=[]
n = len(data)
#Handling first element in the data
#We check if first element is less or equal to the next element
if (data[0] < data[1]):
#if there is, we append the element to the list
dt.append(data[0])
details.append('V')
elif (data[0] > data[1]):
dt.append(data[0])
details.append('P')
else:
#this is checking if the first element is a P
dt.append(data[1])
details.append('N')
#To handle other elements in the data that are not first and last element
for i in range(1, n-1):
if data[i] == data[i-1]==data[i 1]:
dt.append(data[i])
details.append('N')
elif data[i] < data[i-1]<data[i 1]:
dt.append(data[i])
details.append('V')
elif i 1 > n-1 and data[i 1] > data[i-1]:
dt.append(data[i])
details.append('P')
elif (i == 1 or data[i-1] == data[i]) and (i == n-1 or data[i] > data[i 1]): # Found peak
dt.append(data[i])
details.append('P')
elif i-1 > n-1 and data[i 1] < data[i-1]:
dt.append(data[i])
details.append('V')
else:
dt.append(data[i])
details.append('N')
#Handling last element in the data
#We check if the last element is greater or equal to the element before it.
if (data[-1] > data[-2]):
#if there is, we append the element to the list
dt.append(data[-1])
details.append('P')
elif(data[-1] < data[-2]):
#if there is, we append the element to the list
dt.append(data[-1])
details.append('N')
elif(data[-1] >= data[-2]):
#if there is, we append the element to the list
dt.append(data[-1])
details.append('V')
#this is checking if the last element is a V
dt.append(data[-1])
details.append('N')
return dt, details
謝謝
uj5u.com熱心網友回復:
假設:
- 如果峰值嚴格高于前一段和下一段(或兩端只有一個鄰居),則該峰值是一段相同值的最后一個點
- 也就是說,與鄰居相比,谷值對于嚴格較低的值是相同的
- 所有其他點都是“n”
您可以使用itertools.groupby將拉伸與上一個和下一個進行比較:
from itertools import groupby
def pvn(data):
out = []
pos = 0
prev = None
for k, g in groupby(data):
g = list(g)
pos = pos len(g)
next_ = data[pos] if pos < len(data) else None
if (prev is None or k > prev) and (next_ is None or k > next_):
out.extend(['n']*(len(g)-1) ['p'])
elif (prev is None or k < prev) and (next_ is None or k < next_):
out.extend(['n']*(len(g)-1) ['v'])
else:
out.extend(['n']*len(g))
prev = k
return out
pvn([5, 4, 4, 4, 4, 3, 3, 8])
# ['p', 'n', 'n', 'n', 'n', 'n', 'v', 'p']
pvn([2, 1, 4, 5, 5, 5, 4])
# ['p', 'v', 'n', 'n', 'n', 'p', 'v']
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532376.html
標籤:Python算法条件语句
上一篇:使用遞回和記憶理解LCS問題
