Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python whilea&;而A如果B_Python_If Statement_While Loop - Fatal编程技术网

Python whilea&;而A如果B

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:

我正在学习用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:
            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