""" Find All Local Maximums in a list of Integers. An element is a local maximum if it is larger than the two elements adjacent to it, or if it is the first or last element and larger than the one element adjacent to it. Design an algorithm to find all local maxima if they exist. Example: for 3, 2, 4, 1 the local maxima are at indices 0 and 2. """ def FindMaxima(numbers): maxima = [] length = len(numbers) if length >= 2: if numbers[0] > numbers[1]: maxima.append(numbers[0]) if length > 3: for i in range(1, length-1): if numbers[i] > numbers[i-1] and numbers[i] > numbers[i+1]: maxima.append(numbers[i]) if numbers[length-1] > numbers[length-2]: maxima.append(numbers[length-1]) return maxima numbers = [3,2,4,1,7] print FindMaxima(numbers)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question