Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Mountain Peak | Problems
Binary Search in Python

book
Mountain Peak

Have you ever been to the mountains? If not, I hope you still have a chance!

Imagine we have the array with the height of a mountain at specific points. And we need to find the peak value of the mountain in this array.

The peak means that points to the left and right are less than the peak point.

Look at the explanation of the task! How does it work?

Use hints if needed! Be careful with the tabulation!

Oppgave

Swipe to start coding

  1. Set the middle variable. The middle equals the left + (right - left)//2.
  2. Set condition if the right and the left elements are lower or equal to the middle element. The left element: arr[middle - 1]. The right element: arr[middle + 1].
  3. Set condition if the left element is greater than the middle element.
  4. Perform the recursion with the left part of the array.
  5. Perform the recursion with the right part of the array.
  6. Test the function.

Løsning

def peak_binarySearch(arr, left, right, n):

# Set the 'middle' variable
middle = left + (right - left)//2
# Set condition if the right and the left elements are lower or equal the middle element
if ((arr[middle - 1] <= arr[middle]) and (arr[middle + 1] <= arr[middle])):
return middle
# Set condition if the left element is greater than the middle element
elif (arr[middle - 1] > arr[middle]):
# Perform the recursion with the left part of the array
return peak_binarySearch(arr, left, (middle - 1), n)
else:
# Perform the recursion with the right part of the array
return peak_binarySearch(arr, (middle + 1), right, n)
# Testing
arr = [1, 3, 5, 6, 4, 1]
# Test the function using the 'arr'
print(arr[peak_binarySearch(arr, 0, len(arr) - 1, len(arr))])

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 3
def peak_binarySearch(arr, left, right, n):

# Set the 'middle' variable
_ _ _ = _ _ _

# Set condition if the right and the left elements are lower or equal the middle element
if ((arr[middle - 1] <= arr[middle]) and (arr[middle + 1] <= arr[middle])):
return middle

# Set condition if the left element is greater than the middle element
elif (arr[middle - 1] > arr[middle]):
# Perform the recursion with the left part of the array
return peak_binarySearch(arr, left, (middle - 1), n)

else:
# Perform the recursion with the right part of the array
return peak_binarySearch(arr, (middle + 1), right, n)
# Testing
arr = [1, 3, 5, 6, 4, 1]
# Test the function using the 'arr'
print(arr[_ _ _(_ _ _, 0, len(arr) - 1, len(arr))])

Spør AI

expand
ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

We use cookies to make your experience better!
some-alt