Saturday, November 16, 2024
Google search engine
HomeLanguagesPython – Surrounding elements to K

Python – Surrounding elements to K

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




# Python3 code to demonstrate working of
# Surrounding elements to K
# Using index() + loop + try/except
 
# initializing list
test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing K
K = 6
 
res = []
 
for sub in test_list:
 
    # getting index
    try:
        idx = sub.index(K)
    except Exception as e:
        res.append([])
        continue
 
    # Appending Surrounding elements
    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]])
 
# printing result
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




# Python3 code to demonstrate working of
# Surrounding elements to K
# Using index() + in operator + loop
 
# initializing list
test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 6
 
res = []
for sub in test_list:
 
    # getting index
    # checking for element presence in row
    if K in sub:
        idx = sub.index(K)
    else:
        res.append([])
        continue
 
    # appending Surrounding elements
    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]])
 
# printing result
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:

  1. Import the numpy module.
  2. Initialize the original list test_list.
  3. Print the original list.
  4. Initialize the value of K to 6.
  5. Find the length of the longest sublist in test_list using the max() and len() functions.
  6. Create a new list padded_list with all sublists padded with None values to make them of the same length.
  7. Convert the padded_list into a numpy array arr.
  8. Use the where() function to find the indices of K in the array.
  9. Create a boolean array mask of the same shape as arr with all elements set to False.
  10. Use boolean indexing to set the elements before and after K to True in mask.
  11. Extract the elements before and after K from arr using boolean indexing and store them in res.
  12. Remove the None values from the result list res.
  13. Print the result list res.

Python3




# Python3 code to demonstrate working of
# Surrounding elements to K
# Using numpy and boolean indexing
 
# import numpy module
import numpy as np
 
# initializing list
test_list = [[7, 6, 3, 2], [5, 6], [2, 1], [6, 1, 2]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 6
 
# find the length of the longest sublist
max_len = max(map(len, test_list))
 
# create a new list with all sublists padded with None values
padded_list = [sub + [None]*(max_len-len(sub)) for sub in test_list]
 
# convert the padded list into a numpy array
arr = np.array(padded_list)
 
# find the indices of K in the array
idx = np.where(arr == K)
 
# Creating a boolean array indicating the
# elements before and after K
mask = np.zeros(arr.shape, dtype=bool)
mask[idx[0], idx[1]-1] = True
mask[idx[0], idx[1]+1] = True
 
# extract the elements before and after K using boolean indexing
res = [arr[row, mask[row]] for row in range(arr.shape[0])]
 
# remove the None values from the result
res = [[x for x in sub if x is not None] for sub in res]
 
# printing result
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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments