Greater than neighbours. Given a list of numbers, determine and print the number of elements that are greater than both of their neighbors. The first and the last elements of the list should not be considered because they don’t have two neighbors.
|
numbers = list(map(int, input().split())) count = 0 for i in range(1, len(numbers) - 1): if numbers[i] > numbers[i - 1] and numbers[i] > numbers[i + 1]: count += 1 print(count) |
Explanation of the Code
- Reading Input:
numbers = list(map(int, input().split()))
- The
input()
function reads a line of text from the user.
- The
split()
method splits this line into a list of strings based on spaces.
map(int, ...)
converts each string in the list to an integer.
list(...)
converts the map object to a list and stores it in the variable numbers
.
- Iterating Through the List and Counting Elements Greater Than Both Neighbors:
count = 0
for i in range(1, len(numbers) - 1):
if numbers[i] > numbers[i - 1] and numbers[i] > numbers[i + 1]:
count += 1
- Initialize
count
to 0 to keep track of the number of elements that are greater than both neighbors.
- Use a
for
loop to iterate through the list numbers
starting from index 1 to len(numbers) - 2
.
- In each iteration, check if the current element (
numbers[i]
) is greater than both its previous element (numbers[i - 1]
) and its next element (numbers[i + 1]
).
- If the current element is greater than both neighbors, increment
count
by 1.
- Printing the Count of Elements Greater Than Both Neighbors:
- Print the value of
count
after exiting the loop.