【发布时间】:2022-01-14 21:01:34
【问题描述】:
对于给定的列表,如果对于元素a,没有大于a的相邻元素,则称为峰值元素。完成以下函数,该函数返回给定列表 L 的峰值元素列表:
对于 L = [3,2,4,5,4,3,2,2],函数调用 tepeNoktalari(L) 应该返回列表 [3,5,2]。
【问题讨论】:
标签: python arrays python-3.x list arraylist
对于给定的列表,如果对于元素a,没有大于a的相邻元素,则称为峰值元素。完成以下函数,该函数返回给定列表 L 的峰值元素列表:
对于 L = [3,2,4,5,4,3,2,2],函数调用 tepeNoktalari(L) 应该返回列表 [3,5,2]。
【问题讨论】:
标签: python arrays python-3.x list arraylist
def findPeak(L):
results = []
for i in range(1, len(L) - 1):
if L[i] > L[i-1] and L[i] > L[i+1]: # check both sides for each
results.append(L[i]) # ^ element of list excluding edge cases
if L[0] > L[1]: results.append(L[0]) # check edge cases
if L[-1] > L[-2]: results.append(L[-1])
return results
array = [3,2,4,5,4,3,2,2]
print("Peak points are: ", findPeak(array))
【讨论】:
按照这种方法找到峰值元素
【讨论】:
我建议在循环/遍历方法上使用 numpy 解决方案,因为它会更有效。考虑以下几点:
L - np.roll(L, shift=1) # difference with left values
L - np.roll(L, shift=1) > 0 # indices of numbers bigger than left neighbor
L - np.roll(L, shift=1) # difference with right values
L - np.roll(L, shift=1) > 0 # indices of numbers bigger than right neighbor
那么显然我们必须从 L 中取大于它们左右值的数字:这意味着上述索引之间的逻辑与:
L[(L - np.roll(L, shift=1) > 0) & (L - np.roll(L, shift=-1) > 0)]
这仍然导致最后一个元素未正确检查:这是一个简单的修复:
result = L[(L - np.roll(L, shift=1) > 0) & (L - np.roll(L, shift=-1) > 0)]
if L[-1] >= L[-2]:
result = np.append(result, [L[-1]])
【讨论】:
使用 zip 将 L 中的每个项目与前一个和下一个项目组成元组(根据需要使用第一个和最后一个填充)
[x for prevX,x,nextX in zip(L[:1]+L,L,L[1:]+L[-1:]) if prevX <= x >= nextX]
# [3, 5, 2]
【讨论】: