Sunday, November 17, 2024
Google search engine
HomeLanguagesPython | Split K elements after every N values

Python | Split K elements after every N values

The simple list slicing has many applications and along with it many variations of list splitting also exists and can come to us to solve. One such problem can be to split K elements after every N values. Let’s discuss ways in which this particular problem can be solved. 

Method #1 : Using loops This is the Naive and brute force method to solve this particular problem with the help of loop, we can form a new list to check for K occurrences of elements after every N elements. 

Python3




# Python3 code to demonstrate
# Getting K elements after N values
# using loops
 
# initializing list
test_list = [4, 5, 2, 7, 8, 4, 10, 9, 11, 13]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing N and K
N = 2
K = 3
 
# using loops
# Getting K elements after N values
res =[]
while test_list:
    res += test_list[:K]
    test_list = test_list[K + N:]
 
# print result
print("The list after selective slicing : " + str(res))


Output

The original list : [4, 5, 2, 7, 8, 4, 10, 9, 11, 13]
The list after selective slicing : [4, 5, 2, 4, 10, 9]

Time complexity: O(n), where n is the length of the test_list. The loops takes O(n) time
Auxiliary Space: O(n), where n is the number of elements in the list test_list

 Method #2 : Using list comprehension This particular task can be performed using the shortened way of the above method using the list comprehension, we also use list slicing in this method to perform necessary slicing. 

Python3




# Python3 code to demonstrate
# Getting K elements after N values
# using list comprehension
 
# initializing list
test_list = [4, 5, 2, 7, 8, 4, 10, 9, 11, 13]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing N and K
N = 2
K = 3
 
# using list comprehension
# Getting K elements after N values
res = [y for x in [test_list[i : i + K] for i in
       range(0, len(test_list), N + K)] for y in x]
 
# print result
print("The list after selective slicing : " + str(res))


Output

The original list : [4, 5, 2, 7, 8, 4, 10, 9, 11, 13]
The list after selective slicing : [4, 5, 2, 4, 10, 9]

Time complexity: O(n), where n is the length of the test_list.
Auxiliary Space: O(n), where n is the number of elements in the res list.

Method #3 : Using  zip() function 

The zip() function in Python takes iterables (such as lists, tuples, or strings) as input and returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the input iterables.

Here is an example of using the zip() function and slicing to split a list into smaller lists, taking K elements after every N values:

Python3




# Initialize the original list
test_list = [4, 5, 2, 7, 8, 4, 10, 9, 11, 13]
 
# Initialize N and K
N = 2
K = 3
 
# Zip the list with its indices
zipped = zip(test_list, range(len(test_list)))
 
# Use slicing to select the desired elements
result = [x[0] for x in zipped if x[1] % (N + K) < K]
 
# Print the original list and the result
print("The original list : ", test_list)
print("The list after selective slicing : ", result)
#This code is contributed by modalaashwin41


Output

The original list :  [4, 5, 2, 7, 8, 4, 10, 9, 11, 13]
The list after selective slicing :  [4, 5, 2, 4, 10, 9]

The time complexity of this approach is O(n), as it involves iterating through the list once and performing constant-time operations on each element. The space complexity is also O(n), as it involves creating a new list of the same size as the original list.

Approach using numpy:

We can use numpy to create a 2D array from the original list with N rows and K columns, and then flatten it to get the desired output.

Algorithm:

Convert the original list into a numpy array.
Calculate the number of rows in the 2D array using the formula num_rows = ceil(len(test_list)/(N+K)).
Create a 2D numpy array with num_rows rows and K columns using numpy.zeros.
Fill the 2D array with elements from the original list using a loop.
Flatten the 2D array and extract the desired elements.
Print the result.

Python3




import numpy as np
 
# initializing list
test_list = [4, 5, 2, 7, 8, 4, 10, 9, 11, 13]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing N and K
N = 2
K = 3
  
# convert list to numpy array
arr = np.array(test_list)
 
# calculate number of rows
num_rows = np.ceil(len(arr)/(N+K)).astype(int)
 
# create 2D array with zeros
arr_2d = np.zeros((num_rows, K), dtype=int)
 
# fill 2D array with elements from original list
for i in range(num_rows):
    arr_2d[i,:] = arr[i*(N+K) : i*(N+K) + K]
 
# flatten 2D array and extract desired elements
res = arr_2d.flatten()[:num_rows*(N+K)-N]
 
# print result
print("The list after selective slicing : " + str(list(res)))


Output:
The original list : [4, 5, 2, 7, 8, 4, 10, 9, 11, 13]
The list after selective slicing : [4, 5, 2, 4, 10, 9]

Time complexity: O(n), where n is the length of the test_list. The loop takes O(num_rows) time, which is less than or equal to O(n).
Auxiliary Space: O(n), where n is the number of elements in the result list. The 2D array created requires O(num_rows*K) space, which is less than or equal to O(n).

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