Reputation: 2253
I'm completely new to Python, thus the question. I'm trying to solve a standard interview question, which is finding a peak in an array A peak is defined as a number which is greater than it's left and right neighbor. I'm trying to find the largest such peak.
This is my code
#!/usr/bin/python3
def main():
arr = [7, 12, 13, 8, 2, 16, 24, 11, 5, 1]
num = find_peak(arr)
print(num)
def find_peak(arr):
return find_peak(arr, 0, len(arr))
def find_peak(arr, start, stop):
mid = (start + stop)/2
if(arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]):
return arr[mid]
elif (arr[mid] < arr[mid -1]):
find_peak(arr, 0, mid-1)
elif (arr[mid] < arr[mid+1]):
find_peak(arr, mid+1, stop)
if __name__ == '__main__':
main()
This is the error that I'm getting
Traceback (most recent call last):
File "peak.py", line 23, in <module>
main()
File "peak.py", line 5, in main
num = find_peak(arr)
TypeError: find_peak() missing 2 required positional arguments: 'start' and 'stop'
Any help appreciated
Upvotes: 0
Views: 365
Reputation: 97
Overloading is not allowed in Python, my suggestion is to use default values instead of two functions
def find_peak(arr, start = 0, stop = 0):
if stop == 0:
stop = len(arr)
mid = (start + stop)/2
if(arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]):
return arr[mid]
elif (arr[mid] < arr[mid -1]):
find_peak(arr, 0, mid-1)
elif (arr[mid] < arr[mid+1]):
find_peak(arr, mid+1, stop)
Upvotes: 0
Reputation: 61
def main():
arr = [7, 12, 13, 8, 2, 16, 24, 11, 5, 1]
num = find_peak(arr)
print(num)
def find_peak(arr):
return find_peaks(arr, 0, len(arr))
def find_peaks(arr, start, stop):
mid = (start + stop)/2
if(arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]):
return arr[mid]
elif (arr[mid] < arr[mid -1]):
find_peaks(arr, 0, mid-1)
elif (arr[mid] < arr[mid+1]):
find_peaks(arr, mid+1, stop)
if __name__ == '__main__':
main()
Upvotes: 0
Reputation:
You are calling this:
num = find_peak(arr)
But find_peak
takes 3 arguments, as the error states. You have only supplied one.
Unlike C++ or other languages, you cannot have a function with the same name that takes different arguments (also known as function overloading). You can, however, define optional arguments in the function declaration.
Upvotes: 0
Reputation: 23251
You've got two function definitions for find_peak
, one with one argument arr
and the other with three arguments arr
, start
, and stop
. The second one overwrites the first one.
Use two different names for two different functions
Upvotes: 4