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
# Python3 code to demonstrate
# Custom List slicing Sum
# using itertools.islice() + sum() + list comprehension
from itertools import islice
# initializing test list
test_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
# initializing slice list
slice_list = [2, 1, 3, 4]
# printing original list
print("The original list : " + str(test_list))
# printing slice list
print("The slice list : " + str(slice_list))
# using itertools.islice() + sum() + list comprehension
# Custom List slicing Sum
temp = iter(test_list)
res = [sum(list(islice(temp, part))) for part in slice_list]
# print result
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
# Python3 code to demonstrate
# Custom List slicing Sum
# using zip() + accumulate() + sum() + list slicing
from itertools import accumulate
# initializing test list
test_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
# initializing slice list
slice_list = [2, 1, 3, 4]
# printing original list
print("The original list : " + str(test_list))
# printing slice list
print("The slice list : " + str(slice_list))
# using zip() + accumulate() + sum() + list slicing
# Custom List slicing Sum
res = [sum(test_list[i - j: i]) for i, j in zip(accumulate(slice_list), slice_list)]
# print result
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
# Python3 code to demonstrate
# Custom List slicing Sum
# using a loop
# initializing test list
test_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
# initializing slice list
slice_list = [2, 1, 3, 4]
# printing original list
print("The original list : " + str(test_list))
# printing slice list
print("The slice list : " + str(slice_list))
# using a loop
# Custom List slicing Sum
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 result
print("The variable sliced sum list is : " + str(res))
OutputThe 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
# initializing test list
test_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
# initializing slice list
slice_list = [2, 1, 3, 4]
# convert test_list to numpy array
arr = np.array(test_list)
# calculate cumulative sum of the array
cumulative_sum = np.cumsum(arr)
# initialize res list
res = []
# iterate through slice_list
start_index = 0
for slice_len in slice_list:
end_index = start_index + slice_len
# get slice of cumulative sum between start and end indices
slice_cumulative_sum = np.take(cumulative_sum, range(start_index, end_index))
# calculate sliced sum
slice_sum = slice_cumulative_sum[-1] - slice_cumulative_sum[0] + arr[start_index]
# append to res list
res.append(slice_sum)
# update start_index
start_index = end_index
# print result
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
# initializing test list
test_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
# initializing slice list
slice_list = [2, 1, 3, 4]
# printing original list
print("The original list : " + str(test_list))
# printing slice list
print("The slice list : " + str(slice_list))
# using a loop
# Custom List slicing Sum
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 result
print("The variable sliced sum list is : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe 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 - 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 - Sum of Cubes in List
We are having a list we need to find sum of cubes of list. For example, n = [1, 2, 3, 4] we are given this list we need to find sum of cubes of each element of list so that resultant output should be 100.Using List Comprehension with sum()List comprehension with sum() allows us to compute sum of cub
2 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 - Cumulative List Split
Sometimes, while working with String lists, we can have a problem in which we need to perform the task of split and return all the split instances of list in cumulative way. This kind of problem can occur in many domains in which data is involved. Lets discuss certain ways in which this task can be
6 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
Slicing range() function in Python
range() allows users to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.range() takes
2 min read