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!
Uppgift
Swipe to start coding
- Set the
middle
variable. Themiddle
equals theleft + (right - left)//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]
. - Set condition if the left element is greater than the middle element.
- Perform the recursion with the left part of the array.
- Perform the recursion with the right part of the array.
- Test the function.
Lösning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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))])
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 2. Kapitel 3
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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))])
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal