gpt4 book ai didi

python - 查找整数列表中是否存在谷

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:33:26 26 4
gpt4 key购买 nike

A list of integers is said to be a valley if it consists of a sequence of strictly decreasing values followed by a sequence of strictly increasing values. The decreasing and increasing sequences must be of length at least 2. The last value of the decreasing sequence is the first value of the increasing sequence.

Write a Python function valley(l) that takes a list of integers and returns True if l is a valley and False otherwise.

Here are some examples to show how your function should work.

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

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

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

我已经失眠了 2 天,我能写的最好的就是这段代码

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

最佳答案

如果数字不是完美的顺序,我发现的解决方案也有效,并且最低值不必等于 1,我想说的是如果列表假设 [14,12 ,10,5,3,6,7,32,41],这里也形成了一个山谷,因为值下降到 3(最低),然后再次上升。列表如 [4,3,2,1,2,3,4] 是一个完美的山谷。

解决方法:

def valley(lst):
if len(lst)<2:
return False
else:
p = lst.index(min(lst))
for i in range (0,p):
x = (lst[i] > lst[i+1])

for q in range (p,len(lst)-1):
y = (lst[q]< lst[q+1])

return (x==y)

如果解决了问题,对您帮助最大,别忘了采纳,谢谢。

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com