Python | Custom List slicing Sum
Last Updated :
26 Apr, 2023
The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths and its summation according to the input given in other list. This problem has its potential application in web development. Let’s discuss certain ways in which this can be done.
Method #1 : Using itertools.islice() + sum() + list comprehension The list comprehension can be used to iterate through the list and the component issue is solved using the islice function. Summation is performed by sum().
Python3
from itertools import islice
test_list = [ 1 , 5 , 3 , 7 , 8 , 10 , 11 , 16 , 9 , 12 ]
slice_list = [ 2 , 1 , 3 , 4 ]
print ("The original list : " + str (test_list))
print ("The slice list : " + str (slice_list))
temp = iter (test_list)
res = [ sum ( list (islice(temp, part))) for part in slice_list]
print ("The variable sliced sum list is : " + str (res))
|
Output :
The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
The slice list : [2, 1, 3, 4]
The variable sliced sum list is : [6, 3, 25, 48]
Time complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using zip() + accumulate() + sum() + list slicing Apart from using the list comprehension to perform the task of binding, this method uses zip function to hold sublist element together, accumulate function joins the elements, and slicing is used to construct the required slicing. Summation is performed by sum().
Python3
from itertools import accumulate
test_list = [ 1 , 5 , 3 , 7 , 8 , 10 , 11 , 16 , 9 , 12 ]
slice_list = [ 2 , 1 , 3 , 4 ]
print ("The original list : " + str (test_list))
print ("The slice list : " + str (slice_list))
res = [ sum (test_list[i - j: i]) for i, j in zip (accumulate(slice_list), slice_list)]
print ("The variable sliced sum list is : " + str (res))
|
Output :
The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
The slice list : [2, 1, 3, 4]
The variable sliced sum list is : [6, 3, 25, 48]
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
METHOD 3: Using a loop and keeping track of the current slice’s starting and ending indices.
Step-by-step approach:
- Initialize an empty list to store the sliced sums.
- Set the starting index of the current slice to 0.
- Iterate over the slice list.
- For each slice length in the slice list, add the sum of the slice starting from the current index up to the current index plus the slice length.
- Append the sum to the result list.
- Update the current index to be the ending index of the current slice.
- Return the result list.
Below is the implementation of the above approach:
Python3
test_list = [ 1 , 5 , 3 , 7 , 8 , 10 , 11 , 16 , 9 , 12 ]
slice_list = [ 2 , 1 , 3 , 4 ]
print ( "The original list : " + str (test_list))
print ( "The slice list : " + str (slice_list))
res = []
start_index = 0
for slice_len in slice_list:
end_index = start_index + slice_len
slice_sum = sum (test_list[start_index:end_index])
res.append(slice_sum)
start_index = end_index
print ( "The variable sliced sum list is : " + str (res))
|
Output
The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
The slice list : [2, 1, 3, 4]
The variable sliced sum list is : [6, 3, 25, 48]
Time complexity: O(n*m), where n is the length of the test list and m is the length of the slice list.
Auxiliary space: O(m) to store the result list.
Method #4: Using numpy.cumsum() and numpy.take() to get the sliced sum.
- Import numpy module
- Create a numpy array from the test_list
- Calculate the cumulative sum of the numpy array using numpy.cumsum()
- Initialize an empty list res for storing the sliced sum.
- Iterate through the slice_list and for each element in the slice_list:
a. Calculate the start and end index using the previous end index and the current slice length
b. Use numpy.take() to get the slice of the cumulative sum between start and end indices
c. Calculate the sliced sum by taking the difference of the elements in the slice
d. Append the sliced sum to the res list
- Print the res list
Python3
import numpy as np
test_list = [ 1 , 5 , 3 , 7 , 8 , 10 , 11 , 16 , 9 , 12 ]
slice_list = [ 2 , 1 , 3 , 4 ]
arr = np.array(test_list)
cumulative_sum = np.cumsum(arr)
res = []
start_index = 0
for slice_len in slice_list:
end_index = start_index + slice_len
slice_cumulative_sum = np.take(cumulative_sum, range (start_index, end_index))
slice_sum = slice_cumulative_sum[ - 1 ] - slice_cumulative_sum[ 0 ] + arr[start_index]
res.append(slice_sum)
start_index = end_index
print ( "The variable sliced sum list is : " + str (res))
|
OUTPUT:
The variable sliced sum list is : [6, 3, 25, 48]
Time complexity: O(n + m), where n is the length of the test_list and m is the length of the slice_list
Auxiliary space: O(n), where n is the length of the test_list
Method #5: Using heapq:
Algorithm:
- Initialize the test_list and slice_list variables with the given values.
- Print the original and slice list.
- Initialize an empty list res to store the sliced sums.
- Initialize the start_index variable to 0.
- Iterate over the elements of the slice_list using a loop:
- Calculate the end_index by adding the current slice length to the start_index.
- Slice the test_list from the start_index to the end_index.
- Calculate the sum of the sliced elements using the sum() function.
- Append the sum to the res list.
- Update the start_index variable to the end_index for the next iteration.
- Print the res list.
Python3
import heapq
test_list = [ 1 , 5 , 3 , 7 , 8 , 10 , 11 , 16 , 9 , 12 ]
slice_list = [ 2 , 1 , 3 , 4 ]
print ( "The original list : " + str (test_list))
print ( "The slice list : " + str (slice_list))
res = []
start_index = 0
for slice_len in slice_list:
end_index = start_index + slice_len
slice_sum = sum (test_list[start_index:end_index])
res.append(slice_sum)
start_index = end_index
print ( "The variable sliced sum list is : " + str (res))
|
Output
The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
The slice list : [2, 1, 3, 4]
The variable sliced sum list is : [6, 3, 25, 48]
Time complexity:
The time complexity of this algorithm is O(n * m), where n is the length of the test_list and m is the length of the slice_list. This is because we need to iterate over the slice_list and slice the test_list accordingly. The sum() function also takes O(m) time to calculate the sum of the sliced elements.
Space complexity:
The space complexity of this algorithm is O(m), where m is the length of the slice_list. This is because we need to store the sliced sums in the res list, which has a maximum length of m. The space complexity of the test_list and slice_list is not included as they are given inputs.
Similar Reads
Python | Custom list split
Development and sometimes machine learning applications require splitting lists into smaller list in a custom way, i.e on certain values on which split has to be performed. This is quite a useful utility to have knowledge about. Let's discuss certain ways in which this task can be performed. Method
8 min read
Python | Custom sorting in list of tuples
The task of custom sorting in a list of tuples often involves sorting based on multiple criteria. A common example is sorting by the first element in descending order and the second element in ascending order. For example, given a = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)], sorting the tuples by t
3 min read
Slicing List of Tuples in Python
Slicing, a powerful feature in Python, allows us to extract specific portions of data from sequences like lists. When it comes to lists of tuples, slicing becomes a handy tool for extracting and manipulating data. In this article, we'll explore five simple and versatile methods to slice lists of tup
2 min read
Python - Sublist Maximum in custom sliced List
Sometimes, while working with data, we can have a problem in which we need to extract maximum not of whole list but of certain customly broken sublists. This kind of problem is peculiar and occurs in many domains. Let's discuss certain ways in which in which this task can be performed. Method #1 : U
5 min read
Python - Suffix List Sum
Nowadays, especially in the field of competitive programming, the utility of computing suffix sum is quite popular and features in many problems. Hence, having a one-liner solution to it would possess a great help. Letâs discuss the certain way in which this problem can be solved. Method 1: Using li
6 min read
Python | Custom Index Range Summation
Development and sometimes machine learning applications require splitting lists into smaller list in a custom way, i.e on certain values on which split has to be performed and then summation. This is quite a useful utility to have knowledge about. Lets discuss certain ways in which this task can be
7 min read
Python | Splitting list on empty string
Sometimes, we may face an issue in which we require to split a list to list of list on the blank character sent as deliminator. This kind of problem can be used to send messages or can be used in cases where it is desired to have list of list of native list. Let's discuss certain ways in which this
4 min read
Python - Summation of float string list
Sometimes, while working with Python list, we can have a problem in which we need to find summation in list. But sometimes, we donât have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Le
7 min read
Python | Sectional subset sum in list
Some of the classical problems in the programming domain come from different categories and one among them is finding the sum of subsets. This particular problem is also common when we need to accumulate the sum and store consecutive group summations. Let's try different approaches to this problem i
7 min read
Python - Convert 2D list to 3D at K slicing
Sometimes, while working with Python lists, we can have a problem in which we need to convert a 2D list to 3D, at every Kth list. This type of problem is peculiar, but can have application in various data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [[
4 min read