Open In App

Python | Custom Index Range Summation

Last Updated : 09 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate
# Custom Index Range Summation
# using list comprehension + zip() + sum()
 
# initializing string
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
 
# initializing split index list
split_list = [2, 5, 7]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing original split index list
print ("The original split index list : " + str(split_list))
 
# using list comprehension + zip() + sum()
# Custom Index Range Summation
res = [sum(test_list[i : j]) for i, j in zip([0] +
                 split_list, split_list + [None])]
 
# printing result
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




# Python3 code to demonstrate
# Custom Index Range Summation
# using itertools.chain() + zip()
from itertools import chain
 
# initializing string
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
 
# initializing split index list
split_list = [2, 5, 7]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing original split index list
print ("The original split index list : " + str(split_list))
 
# using itertools.chain() + zip()
# Custom Index Range Summation
temp = zip(chain([0], split_list), chain(split_list, [None]))
res = list(sum(test_list[i : j]) for i, j in temp)
 
# printing result
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
 
# initializing list
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
   
# initializing split index list
split_list = [2, 5, 7]
   
# printing original list
print ("The original list is : " + str(test_list))
   
# printing original split index list
print ("The original split index list : " + str(split_list))
   
# using numpy.split() + numpy.sum()
# Custom Index Range Summation
res = [np.sum(split) for split in np.split(test_list, split_list)]
   
# printing result
print ("The splitted lists summation are : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


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 = []  # initialize an empty list to store the results
start = 0  # initialize the starting index for slicing the original list
for end in split_list:  # iterate through the split index list
    # slice the original list from start to end, compute the sum, and append it to the result list
    result.append(sum(test_list[start:end]))
    start = end  # update the starting index for the next slice
 
# slice the original list from the last split index to the end, compute the sum, and append it to the result list
result.append(sum(test_list[start:]))
print("The splitted lists summation are : " + str(result))  # print the 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
 
# Initializing the input list
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
 
# Initializing the split index list
split_list = [2, 5, 7]
 
# Initializing an empty list to store the sum of each sublist
result = []
 
# Initializing a variable to keep track of the starting index of each sublist
start = 0
 
# Looping through the split index list to compute the sum of each sublist
for end in split_list + [len(test_list)]:
    # Using the reduce function to compute the sum of the current sublist
    # The lambda function takes two arguments and returns their sum
    # reduce() applies this function to each element of the sublist in a cumulative way
    # and returns the final result
    sublist_sum = reduce(lambda x, y: x + y, test_list[start:end])
    # Appending the sum of the current sublist to the result list
    result.append(sublist_sum)
    # Updating the starting index of the next sublist
    start = end
 
# Printing the result
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. 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads