jeudi 5 novembre 2020

Difference between While A & B and While A if B

I am learning to find the longest peak in an array with Python. This is the workable code:

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

Now when I tried to do it by myself, I changed this part:

        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

into:

    leftIdx = i - 2
    while leftIdx >= 0:
        if array[leftIdx] < array[leftIdx + 1]:
            leftIdx -= 1
    rightIdx = i + 2
    while rightIdx <= len(array) - 1:
        if array[rightIdx] < array[rightIdx - 1]:
            rightIdx += 1

Then I go into infinite loop, I am still confused now... Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire