Python 如何找到这个转折点
请帮助完成这个算法。 我有一个值为1,2,4,5,4,3,7,8,10,4,5,3,-2,-3的数组 如果像图表一样看待它们,那么我们就有了这样的图表Python 如何找到这个转折点,python,arrays,algorithm,Python,Arrays,Algorithm,请帮助完成这个算法。 我有一个值为1,2,4,5,4,3,7,8,10,4,5,3,-2,-3的数组 如果像图表一样看待它们,那么我们就有了这样的图表 (原始链接:) 如何找到这个转折点?所以在变为0或更低之前,最后一个最大正值。抱歉,我不知道如何更好地描述。这里有一个算法,可以满足您的需要 从末尾开始,迭代各点,直到找到负值或到达起点。如果你到达起点,那么就没有转折点。否则,继续执行步骤2 值为负值时继续迭代。如果你到达起点,那么就没有转折点。否则,将找到的正值记录为candidate,并将其
(原始链接:)
如何找到这个转折点?所以在变为0或更低之前,最后一个最大正值。抱歉,我不知道如何更好地描述。这里有一个算法,可以满足您的需要
candidate
,并将其索引记录为candidate\u index
,然后继续执行步骤3candidate
时继续迭代,更新candidate
及其索引为candidate\u index
。如果该值不大于此值,或者到达起点,则完成。转折点是candidate
,其索引是candidate\u index
请尝试测试此代码。让我们猜测您的arr列表是[1,2,4,5,4,3,7,8,10,4,5,3,-2,-3]
def lastTurningPointIndex(arr)
arr = [1,2,4,5,4,3,7,8,10,4,5,3,-2,-3]
for i in range(len(arr)-1, -1, -1):
if arr[i] > 0:
if (arr[i-1] < arr[i]):
return i
def lastTurningPointIndex(arr)
arr=[1,2,4,5,4,3,7,8,10,4,5,3,-2,-3]
对于范围内的i(len(arr)-1,-1,-1):
如果arr[i]>0:
如果(arr[i-1]
零线交叉旋转几次是否可能?像[1,2,4,5,4,3,-7,-8,10,4,5,3,-2,-3]
我以你为例,假设一个零交叉点
def find_point(sequence: list) -> tuple:
"""Find the point of maximum value before crossing the zero line."""
max_value = 0 # init max_value
for i, value in enumerate(sequence):
# iterate though the points until you find a negative value
if value < 0: # <-- negative value
for y, rvalue in enumerate(reversed(sequence[:i])):
# slice the sequence from start to negative value --> [1, 2, 4, 5, 4, 3, 7, 8, 10, 4, 5, 3]
# reversed --> [3, 5, 4, 10, 8, 7, 3, 4, 5, 4, 2, 1]
# iterate though the points while the next value are larger than max_value
if rvalue >= max_value:
# updating max_value
max_value = rvalue
else:
# when next value are less then max_value, got it
# return max_value and point [count to point starts from zero!]
return max_value, i - y
使用
for
循环。值得一提的是,这将找到一系列中的最后一个转折点。请解释代码的作用和作用方式。
sequence = [1, 2, 4, 5, 4, 3, 7, 8, 10, 4, 5, 3, -2, -3]
value, point = find_point(sequence=sequence)
print(value, point, value == sequence[point]) # 5 10 True