Python whilea&;而A如果B
我正在学习用Python查找数组中最长的峰值。 这是可行的代码:Python whilea&;而A如果B,python,if-statement,while-loop,Python,If Statement,While Loop,我正在学习用Python查找数组中最长的峰值。 这是可行的代码: def longestPeak(array): i = 1 currentPeakLength = 0 longestPeakLength = 0 while i < len(array) - 1: isPeak = array[i] > array[i - 1] and array[i] > array[i + 1] if not isPeak:
def longestPeak(array):
i = 1
currentPeakLength = 0
longestPeakLength = 0
while i < len(array) - 1:
isPeak = array[i] > array[i - 1] and array[i] > array[i + 1]
if not isPeak:
i += 1
continue
leftIdx = i - 2
while leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1]:
leftIdx -= 1
rightIdx = i + 2
while rightIdx <= len(array) - 1 and array[rightIdx] < array[rightIdx - 1]:
rightIdx += 1
currentPeakLength = rightIdx - leftIdx - 1
if currentPeakLength > longestPeakLength:
longestPeakLength = currentPeakLength
i = rightIdx
return longestPeakLength
def最长峰值(阵列):
i=1
currentPeakLength=0
最长峰值长度=0
而iarray[i-1]和array[i]>array[i+1]
如果不是isPeak:
i+=1
持续
leftIdx=i-2
当leftIdx>=0且数组[leftIdx]
现在,当我试图自己做这件事时,我改变了这一部分:
leftIdx = i - 2
while leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1]:
leftIdx -= 1
rightIdx = i + 2
while rightIdx <= len(array) - 1 and array[rightIdx] < array[rightIdx - 1]:
rightIdx += 1
leftIdx=i-2
当leftIdx>=0且数组[leftIdx] 而rightIdx在这里假设leftIdx>=0
当前为True
:
while leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1]:
leftIdx -= 1
将使循环继续,但不为该迭代执行leftIdx-=1
。while条件控制循环何时结束。在第二个版本中,如果while条件为true,if条件为false,则不会更新leftIdx
,循环是无限的。在第一个版本中,如果其中一个条件为false,循环将立即退出。
while leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1]:
leftIdx -= 1
while leftIdx >= 0:
if array[leftIdx] < array[leftIdx + 1]:
leftIdx -= 1