Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Replacing by Greatest Neighbors in a List
When it is required to replace elements of a list by their greatest neighbors, a simple iteration along with the 'if' and 'else' condition is used. Each element (except the first and last) gets replaced by whichever neighbor has the greater value.
Syntax
The general approach involves iterating through the list and comparing adjacent elements ?
for index in range(1, len(list) - 1):
list[index] = list[index - 1] if list[index - 1] > list[index + 1] else list[index + 1]
Example
Below is a demonstration of replacing elements by their greatest neighbors ?
numbers = [41, 25, 24, 45, 86, 37, 18, 99]
print("The original list is:")
print(numbers)
for index in range(1, len(numbers) - 1):
numbers[index] = numbers[index - 1] if numbers[index - 1] > numbers[index + 1] else numbers[index + 1]
print("The resultant list is:")
print(numbers)
The original list is: [41, 25, 24, 45, 86, 37, 18, 99] The resultant list is: [41, 41, 45, 86, 86, 86, 99, 99]
How It Works
The algorithm processes each element from index 1 to n-2 (excluding first and last elements) ?
For index 1: Compare neighbors 41 and 24 ? 41 is greater ? Replace 25 with 41
For index 2: Compare neighbors 25 and 45 ? 45 is greater ? Replace 24 with 45
For index 3: Compare neighbors 24 and 86 ? 86 is greater ? Replace 45 with 86
This continues until all middle elements are processed
Using List Comprehension
You can also achieve the same result using list comprehension for a more concise approach ?
numbers = [41, 25, 24, 45, 86, 37, 18, 99]
print("Original list:", numbers)
result = [numbers[0]] + [max(numbers[i-1], numbers[i+1]) for i in range(1, len(numbers)-1)] + [numbers[-1]]
print("Result list:", result)
Original list: [41, 25, 24, 45, 86, 37, 18, 99] Result list: [41, 41, 45, 86, 86, 86, 99, 99]
Conclusion
Replacing elements by their greatest neighbors involves comparing left and right neighbors for each middle element. The first and last elements remain unchanged as they don't have both neighbors.
