Python 是否有任何方法可以确定列表中的元素是否先增加后减少?

Python 是否有任何方法可以确定列表中的元素是否先增加后减少?,python,python-3.x,function,Python,Python 3.x,Function,我需要找到一个列表是真是假,其中的数字是递增顺序,然后是递减顺序 或按降序和升序排列的数字。 您可以假设输入序列中的连续数字总是彼此不同 我尝试了以下代码,但无法获得适当的返回值,即(真/假) 有人能就如何改进我的代码给出一些建议吗 def hillvalley(A): return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or all(A[i] >= A[i + 1] for i in rang

我需要找到一个列表是真是假,其中的数字是递增顺序,然后是递减顺序

或按降序和升序排列的数字。 您可以假设输入序列中的连续数字总是彼此不同

我尝试了以下代码,但无法获得适当的返回值,即(真/假) 有人能就如何改进我的代码给出一些建议吗

def hillvalley(A): 

    return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or
        all(A[i] >= A[i + 1] for i in range(len(A) - 1))) 

hillvalley([1,2,3,5,4,3,2,1])
def hillvalley(A):
返回(范围(len(A)-1)内i的全部(A[i]=A[i+1]))
山巷([1,2,3,5,4,3,2,1])
这假设不存在“高原”(或两个连续元素相等的情况)。如果您想说明这一点,我将把它作为一个练习留给您相应地修改此代码

def hillvalley(A):
    # determine which direction we're going
    orig_direction = (A[1] > A[0])
    # make a flag for when we switch directions (hill-to-valley, or valley-to-hill)
    switched_direction = orig_direction
    # do comparisons to the last element:
    last = A[1]
    for e in A[2:]:
        # determine our current direction
        current_direction = (e > last)
        # are we still moving the same direction as we were last time?
        if current_direction != switched_direction:
            # if not, then determine how many times we're changing direction
            if switched_direction == orig_direction:
                # this is the first time we're changing direction, so it's fine
                switched_direction = current_direction
            else:
                # this is the second time, which means it fails the test
                return False
        last = e
    # if we don't return during any of that, then it passes the test
    return True

通过查找最大值和最小值的索引来工作

对于递增,然后递减,检查最大索引的值是否递增,然后递减

对于递减,然后是递增检查,直到最小索引的值先递减,然后递增

能够应付高原

代码

def hillvalley(A):
  # Check increasing followed by decreasing
  index, _ = max(enumerate(A), key=lambda v: v[1])
  if all(A[i]<=A[i+1] for i in range(index)) and \
    all(A[i]>=A[i+1] for i in range(index, len(A)-1)):
    return True

  # Check decreasing followed by increasing
  index, _ = min(enumerate(A), key=lambda v: v[1])
  if all(A[i]>=A[i+1] for i in range(index)) and \
    all(A[i]<=A[i+1] for i in range(index, len(A)-1)):
    return True

  return False
输出

for t in [[1,2,3,5,4,3,2,1], [4,3,2,1,1,2,3,5], [1,2,1,5,4,3,2,1]]:
  print(f'{t} -> {hillvalley(t)}')
[1, 2, 3, 5, 4, 3, 2, 1] -> True
[4, 3, 2, 1, 1, 2, 3, 5] -> True
[1, 2, 1, 5, 4, 3, 2, 1] -> False

大家好,欢迎来到SO,请提供一个示例,包括输入和预期输出。它在哪些测试中失败?你期望什么?实际发生了什么?
[1, 2, 3, 5, 4, 3, 2, 1] -> True
[4, 3, 2, 1, 1, 2, 3, 5] -> True
[1, 2, 1, 5, 4, 3, 2, 1] -> False