Python – Surrounding elements to K
Last Updated :
27 Apr, 2023
Given Matrix, from each row, get surrounding elements of K, if present.
Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]], K = 6
Output : [[7, 3], [5], [], [1]]
Explanation : All elements surrounded by 6 are extracted.
Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]], K = 1
Output : [[], [], [2], [6, 2]]
Explanation : All elements surrounded by 1 are removed.
Method #1: Using index() + loop + try/except
In this, we check for the index of elements using index() and then get the required surrounding elements by accessing next and previous elements. If the element is not present, an empty list is returned.
Python3
test_list = [[ 7 , 6 , 3 , 2 ], [ 5 , 6 ], [ 2 , 1 ], [ 6 , 1 , 2 ]]
print ( "The original list is : " + str (test_list))
K = 6
res = []
for sub in test_list:
try :
idx = sub.index(K)
except Exception as e:
res.append([])
continue
if idx ! = 0 and idx ! = len (sub) - 1 :
res.append([sub[idx - 1 ], sub[idx + 1 ]])
elif idx = = 0 :
res.append([sub[idx + 1 ]])
else :
res.append([sub[idx - 1 ]])
print ( "The Surrounding elements : " + str (res))
|
Output
The original list is : [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]
The Surrounding elements : [[7, 3], [5], [], [1]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using index() + in operator + loop
In this, we check if the element is present in a row before application of index(), to avoid using try/except block. Rest all functionalities are the same as the above method.
Python3
test_list = [[ 7 , 6 , 3 , 2 ], [ 5 , 6 ], [ 2 , 1 ], [ 6 , 1 , 2 ]]
print ( "The original list is : " + str (test_list))
K = 6
res = []
for sub in test_list:
if K in sub:
idx = sub.index(K)
else :
res.append([])
continue
if idx ! = 0 and idx ! = len (sub) - 1 :
res.append([sub[idx - 1 ], sub[idx + 1 ]])
elif idx = = 0 :
res.append([sub[idx + 1 ]])
else :
res.append([sub[idx - 1 ]])
print ( "The Surrounding elements : " + str (res))
|
Output
The original list is : [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]
The Surrounding elements : [[7, 3], [5], [], [1]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using numpy and boolean indexing
Approach:
- Import the numpy module.
- Initialize the original list test_list.
- Print the original list.
- Initialize the value of K to 6.
- Find the length of the longest sublist in test_list using the max() and len() functions.
- Create a new list padded_list with all sublists padded with None values to make them of the same length.
- Convert the padded_list into a numpy array arr.
- Use the where() function to find the indices of K in the array.
- Create a boolean array mask of the same shape as arr with all elements set to False.
- Use boolean indexing to set the elements before and after K to True in mask.
- Extract the elements before and after K from arr using boolean indexing and store them in res.
- Remove the None values from the result list res.
- Print the result list res.
Python3
import numpy as np
test_list = [[ 7 , 6 , 3 , 2 ], [ 5 , 6 ], [ 2 , 1 ], [ 6 , 1 , 2 ]]
print ( "The original list is : " + str (test_list))
K = 6
max_len = max ( map ( len , test_list))
padded_list = [sub + [ None ] * (max_len - len (sub)) for sub in test_list]
arr = np.array(padded_list)
idx = np.where(arr = = K)
mask = np.zeros(arr.shape, dtype = bool )
mask[idx[ 0 ], idx[ 1 ] - 1 ] = True
mask[idx[ 0 ], idx[ 1 ] + 1 ] = True
res = [arr[row, mask[row]] for row in range (arr.shape[ 0 ])]
res = [[x for x in sub if x is not None ] for sub in res]
print ( "The Surrounding elements : " + str (res))
|
Output
The original list is : [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]
The Surrounding elements : [[7, 3], [5], [], [1]]
Time complexity: O(n*m), where n is the number of sublists in test_list and m is the length of the longest sublist.
Auxiliary space: O(n*m), where n is the number of sublists in test_list and m is the length of the longest sublist.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...