Python – Replacing by Greatest Neighbour in list
Last Updated :
28 Feb, 2023
Given a list, the task is to write a Python program to replace with the greatest neighbor among previous and next elements.
Input : test_list = [5, 4, 2, 5, 8, 2, 1, 9],
Output : [5, 5, 5, 8, 8, 8, 9, 9]
Explanation : 4 is having 5 and 2 as neighbours, replaced by 5 as greater than 2.
Input : test_list = [5, 4, 2, 5],
Output : [5, 5, 5, 5]
Explanation : 4 is having 5 and 2 as neighbours, replaced by 5 as greater than 2.
Method 1 : Using loop + chain conditional statements
In this, we use loop to iterate through all the elements in list and check for neighbours for greater element using conditionals and then is replaced.
Python3
test_list = [ 5 , 4 , 2 , 5 , 8 , 2 , 1 , 9 ]
print ( "The original list is : " + str (test_list))
for idx in range ( 1 , len (test_list) - 1 ):
test_list[idx] = test_list[idx - 1 ] \
if test_list[idx - 1 ] > test_list[idx + 1 ] \
else test_list[idx + 1 ]
print ( "The elements after replacing : " + str (test_list))
|
Output:
The original list is : [5, 4, 2, 5, 8, 2, 1, 9]
The elements after replacing : [5, 5, 5, 8, 8, 8, 9, 9]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2 : Using max() + loop.
In this, we get the maximum element among neighbouring elements using max(). The loop is used to iterate through the elements.
Python3
test_list = [ 5 , 4 , 2 , 5 , 8 , 2 , 1 , 9 ]
print ( "The original list is : " + str (test_list))
for idx in range ( 1 , len (test_list) - 1 ):
test_list[idx] = max (test_list[idx - 1 ], test_list[idx + 1 ])
print ( "The elements after replacing : " + str (test_list))
|
Output:
The original list is : [5, 4, 2, 5, 8, 2, 1, 9]
The elements after replacing : [5, 5, 5, 8, 8, 8, 9, 9]
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...