如果一个整数列表由一个严格递减的值序列和一个严格递增的值序列组成,那么它就是一个谷。递减和递增序列的长度必须至少为2。递减序列的最后一个值是递增序列的第一个值。
编写一个Python函数valley(l),它接受一个整数列表,如果l是valley则返回True,否则返回False。
这里有一些例子来说明您的函数应该如何工作。

>>> valley([3,2,1,2,3])
True

>>> valley([3,2,1])
False

>>> valley([3,3,2,1,2])
False

我已经失眠两天了,我能写的最好的就是这段代码
def valley(list):
    first =False
    second=False
    midway=0
    if(len(list)<2):
        return False
    else:
        for i in range(0,len(list)):
            if(list[i]<list[i+1]):
                first=True
                midway=i
                break
        for j in range(midway,len(list)-1):
            if(list[j]<list[j+1] and j+1==len(list)):
                Second=True
                break
            if(list[j]>=list[j+1]):
                second=False
                break
    if(first==True and second==True):
        return True
    else:
        return False

最佳答案

似乎比我更厉害,但如果你能给我点魔法的话:

import numpy as np


def valley(arr):
    diff = arr[:-1] - arr[1:]

    gt = np.where(diff > 0)[0]
    lt = np.where(diff < 0)[0]
    d = np.sum(diff == 0)

    if gt.size == 0 or lt.size == 0:
        # Doesn't have ascendings or decendings
        return False
    elif d > 0:
        # Has a flat
        return False
    elif gt[-1] > lt[0]:
        # Not strictly one descent into one ascent
        return False
    else:
        return True

a = np.array([3, 2, 1, 2, 3])
b = np.array([3, 3, 2, 1, 2])
c = np.array([3, 2, 1])
d = np.array([1, 2, 3, 2, 1])

print(valley(a), valley(b), valley(c), valley(d))
>>> True False False False

您还可以使用普通的旧python内置函数来执行此操作:
def valley(arr):
    diff = [i1-i2 for i1, i2 in zip(arr, arr[1:])]

    gt = [i for i, item in enumerate(diff) if item > 0]
    lt = [i for i, item in enumerate(diff) if item < 0]
    d = sum([True for d in diff if d == 0])

    if len(gt) == 0 or len(lt) == 0:
        # Doesn't have ascendings or decendings
        return False
    elif d > 0:
        # Has a flat
        return False
    elif gt[-1] > lt[0]:
        # Not strictly one descent into one ascent
        return False
    else:
        return True

a = [3, 2, 1, 2, 3]
print(valley(a), ...)
>>> True False False False

关于python - 查找在整数列表中是否存在谷,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52238780/

10-09 21:20