Python | Custom Index Range Summation
Last Updated :
09 Apr, 2023
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 performed.
Method #1: Using list comprehension + zip() + sum() By coupling the power of list comprehension and zip(), this task can be achieved. In this we zip beginning and end of list and then keep slicing the list as they arrive and cutting off new lists from them. The task of finding summation is performed using sum().
Python3
test_list = [ 1 , 4 , 5 , 6 , 7 , 3 , 5 , 9 , 2 , 4 ]
split_list = [ 2 , 5 , 7 ]
print ("The original list is : " + str (test_list))
print ("The original split index list : " + str (split_list))
res = [ sum (test_list[i : j]) for i, j in zip ([ 0 ] +
split_list, split_list + [ None ])]
print ("The splitted lists summation are : " + str (res))
|
Output :
The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
The original split index list : [2, 5, 7]
The splitted lists summation are : [5, 18, 8, 15]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using itertools.chain() + zip() + sum() The task performed by the list comprehension function of getting the split chunks can also be done using chain function. This is more useful when we wish to handle larger lists as this method is more efficient. The task of finding summation is performed using sum().
Python3
from itertools import chain
test_list = [ 1 , 4 , 5 , 6 , 7 , 3 , 5 , 9 , 2 , 4 ]
split_list = [ 2 , 5 , 7 ]
print ("The original list is : " + str (test_list))
print ("The original split index list : " + str (split_list))
temp = zip (chain([ 0 ], split_list), chain(split_list, [ None ]))
res = list ( sum (test_list[i : j]) for i, j in temp)
print ("The splitted lists summations are : " + str (res))
|
Output :
The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
The original split index list : [2, 5, 7]
The splitted lists summation are : [5, 18, 8, 15]
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 numpy.split() + numpy.sum()
Note: Install numpy module using command “pip install numpy”
This method is using numpy library which makes the process of splitting and summation very simple and efficient.
Python3
import numpy as np
test_list = [ 1 , 4 , 5 , 6 , 7 , 3 , 5 , 9 , 2 , 4 ]
split_list = [ 2 , 5 , 7 ]
print ( "The original list is : " + str (test_list))
print ( "The original split index list : " + str (split_list))
res = [np. sum (split) for split in np.split(test_list, split_list)]
print ( "The splitted lists summation are : " + str (res))
|
Output:
The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
The original split index list : [2, 5, 7]
The splitted lists summation are : [5, 18, 8, 15]
Time complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using a loop and slicing
This method uses a loop to iterate through the split index list and slice the original list based on the indices. The sum of each slice is then appended to the result list.
Python3
test_list = [ 1 , 4 , 5 , 6 , 7 , 3 , 5 , 9 , 2 , 4 ]
split_list = [ 2 , 5 , 7 ]
result = []
start = 0
for end in split_list:
result.append( sum (test_list[start:end]))
start = end
result.append( sum (test_list[start:]))
print ( "The splitted lists summation are : " + str (result))
|
Output
The splitted lists summation are : [5, 18, 8, 15]
Time Complexity: O(n)
- The algorithm iterates through the split index list once, which takes O(k) time, where k is the length of the split index list.
- For each split index, the algorithm computes the sum of a slice of the original list, which takes O(n/k) time on average, where n is the length of the original list.
- Therefore, the overall time complexity of the algorithm is O(k * n/k) = O(n).
Auxiliary Space: O(k)
- The algorithm uses an additional list to store the results, which can have at most k elements, where k is the length of the split index list.
- Therefore, the overall space complexity of the algorithm is O(k).
Method #5: Using the reduce() function from functools module
The reduce() function can be used to apply a function to a sequence of values and return a single value. We can use it in combination with the split index list to compute the sum of each sublist. Here’s an implementation using reduce():
Python3
from functools import reduce
test_list = [ 1 , 4 , 5 , 6 , 7 , 3 , 5 , 9 , 2 , 4 ]
split_list = [ 2 , 5 , 7 ]
result = []
start = 0
for end in split_list + [ len (test_list)]:
sublist_sum = reduce ( lambda x, y: x + y, test_list[start:end])
result.append(sublist_sum)
start = end
print ( "The splitted lists summation are: " + str (result))
|
Output
The splitted lists summation are: [5, 18, 8, 15]
Time complexity: O(n * m), where n is the length of the input list and m is the number of split indices. This is because we need to loop through the split index list and apply the reduce function to each sublist.
Auxiliary space: O(m), where m is the number of split indices.
Similar Reads
Summation Matrix columns - Python
The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
2 min read
Element indices Summation - Python
Our task is to calculate the sum of elements at specific indices in a list. This means selecting elements at specific positions and computing their sum. Given a list and a set of indices, the goal is to compute the sum of elements present at those indices. For example, given the list [10, 20, 30, 40
3 min read
Python - Consecutive Row summation in Matrix
This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the sum between the like indices when compared with the next list. The sum between the like elements in that index is returned. Letâs discuss certain ways in which t
5 min read
Python | Custom List slicing Sum
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. Me
7 min read
Python | Selective indices Summation
Accessing an element from its index is easier task in python, just using the [] operator in a list does the trick. But in certain situations we are presented with tasks when we have more than once indices and we need to get all the elements corresponding to those indices and then perform the summati
6 min read
Python - Custom Tuple Key Summation in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform group summation of values, of certain key on particular index of tuple keys of dictionary. This problem is quite custom, but can have application in domains that revolves around data processing. Let'
7 min read
Python - Index Value Summation List
To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that, we may need to employ different strategies. This article discusses some of those strategies. Method 1: Nai
4 min read
Python - Sort by range inclusion
Given a range, sort tuple Matrix by total range covered in a given range. [Considering tuples which completely lie within range]. Input : test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]], i, j = 2, 15 Output : [[(3, 16)], [(1, 5), (6, 10), (10, 15)],
4 min read
Python - Tuple Matrix Columns Summation
Sometimes, while working with Tuple Matrix, we can have a problem in which we need to perform summation of each column of tuple matrix, at the element level. This kind of problem can have application in Data Science domains. Let's discuss certain ways in which this task can be performed. Input : tes
8 min read
Python | Cumulative Columns summation of Records
Sometimes, while working with records, we can have a problem in which we need to sum all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using sum() + list
7 min read