Python | Accumulative index summation in tuple list
Last Updated :
16 May, 2023
Sometimes, while working with data, we can have a problem in which we need to find accumulative summation of each index in tuples. This problem can have applications in web development and competitive programming domain. Let's discuss certain way in which this problem can be solved.
Method 1: Using accumulate() + sum() + lambda + map() + tuple() + zip() The combination of above functions can be used to solve this task. In this, we pair the elements using zip(), then we perform the sum of them and we extend this to all elements using map(). The taking forward of sum is done by using accumulate. The binding of all logic is done by lambda function.
Python3
# Python3 code to demonstrate working of
# Accumulative index summation in tuple list
# Using accumulate() + sum() + lambda + map() + tuple() + zip()
from itertools import accumulate
# initialize list
test_list = [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
# printing original list
print("The original list : " + str(test_list))
# Accumulative index summation in tuple list
# Using accumulate() + sum() + lambda + map() + tuple() + zip()
res = list(accumulate(test_list, lambda i, j: tuple(map(sum, zip(i, j)))))
# printing result
print("Accumulative index summation of tuple list : " + str(res))
OutputThe original list : [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
Accumulative index summation of tuple list : [(3, 4, 5), (7, 9, 12), (8, 13, 22)]
Time complexity: O(nm), where n is the number of tuples in the list and m is the length of each tuple. This is because the program iterates over each tuple in the list once and performs an operation on each element of the tuple.
Auxiliary space: O(nm), as the program creates a new list of tuples to store the result of the operation performed on each tuple in the original list.
Method #2: Using numpy.cumsum()
Note: Install numpy module using command "pip install numpy"
This method uses the cumsum() function from the numpy library to perform the cumulative sum of the tuple list. This function takes the input array and performs the cumulative sum along the specified axis.
Python3
import numpy as np
# initialize list
test_list = [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
# printing original list
print("The original list : " + str(test_list))
# Using numpy.cumsum()
res = np.cumsum(test_list, axis=0)
# printing result
print("Accumulative index summation of tuple list : " + str([tuple(i) for i in res]))
#This code is contributed by Edula Vinay Kumar Reddy
Output :
The original list : [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
Accumulative index summation of tuple list : [(3, 4, 5), (7, 9, 12), (8, 13, 22)]
Time Complexity : O(n)
Auxiliary Space : O(n)
Method 3: Using list comprehension
Use a loop to iterate over the tuples in the test_list. For each iteration, extract the first i+1 tuples from the test_list and use the zip function to group the elements with the same index into tuples. then calculate the sum of each of these tuples using a list comprehension and the sum function. Finally, we convert the resulting list of sums into a tuple using the tuple function and append it to the cumulative_sum list.
Python3
test_list = [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
# Initialize an empty list to store the cumulative sums
cumulative_sum = []
# Loop over the tuples in the test_list
for i in range(len(test_list)):
# Extract the i+1 tuples from the test_list and calculate the sum of each element
temp_sum = tuple(sum(y) for y in zip(*test_list[:i+1]))
# Append the cumulative sum to the list
cumulative_sum.append(temp_sum)
print("Accumulative index summation of tuple list : " + str(cumulative_sum))
OutputAccumulative index summation of tuple list : [(3, 4, 5), (7, 9, 12), (8, 13, 22)]
Time complexity: O(n^2), where n is the number of tuples in the test_list.
Auxiliary space: O(n^2), as we store the cumulative sums in a list that has the same length as the test_list.
Method 4: Using a for loop to iterate over the tuples and calculate the cumulative index summation.
The implementation uses a for loop to iterate over the tuples in the list. If the result list is empty, the current tuple is appended to the result. Otherwise, the previous tuple in the result is retrieved and a new tuple is calculated by adding the corresponding elements of the two tuples. The new tuple is then appended to the result list.
Python3
# initialize list
test_list = [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
# printing original list
print("The original list : " + str(test_list))
# Accumulative index summation in tuple list
# Using for loop
res = []
for tup in test_list:
if not res:
res.append(tup)
else:
last_tup = res[-1]
new_tup = tuple(last_tup[i] + tup[i] for i in range(len(tup)))
res.append(new_tup)
# printing result
print("Accumulative index summation of tuple list : " + str(res))
OutputThe original list : [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
Accumulative index summation of tuple list : [(3, 4, 5), (7, 9, 12), (8, 13, 22)]
Time complexity: O(n*m), where n is the number of tuples in the list and m is the length of each tuple.
Auxiliary space: O(n*m), where n is the number of tuples in the list and m is the length of each tuple.
Method 5: Using itertools.accumulate()
Use the accumulate() function from the itertools module to calculate the cumulative sum of each tuple element-wise. Here's how you can do it:
- Create a list test_list of tuples, each tuple containing three integers.
- Call the accumulate() function from the itertools module with two arguments: the test_list list and a lambda function that takes two tuples as input and returns a new tuple that is the element-wise sum of the two input tuples.
- The accumulate() function returns an iterator that generates the cumulative sums of the tuples in the input list. Convert this iterator to a list using the list() function and assign it to the variable res.
- Print the res list, which contains the cumulative sums of the tuples in the input list.
Python3
import itertools
test_list = [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
res = list(itertools.accumulate(test_list, lambda x, y: tuple(xi + yi for xi, yi in zip(x, y))))
print("Accumulative index summation of tuple list : " + str(res))
OutputAccumulative index summation of tuple list : [(3, 4, 5), (7, 9, 12), (8, 13, 22)]
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), because the accumulate() function returns a new list that contains the cumulative sums.
Method 6: Using Recursive method.
Step-by-step approach:
- Initialize an empty list res to store the result.
- Loop through all the tuples in the list.
- If this is the first tuple, append it to the result list.
- Otherwise, get the last tuple in the result list.
- Create a new tuple by adding the corresponding elements of the current tuple and the last tuple.
- Append the new tuple to the result list.
- Return the result list.
Python3
def accumulative_sum(tuples, index=0, accumulative_tuple=()):
if index == len(tuples): # base case - reached the end of the list
return []
else:
tup = tuples[index]
if not accumulative_tuple: # if this is the first tuple
new_tup = tup
else:
new_tup = tuple(accumulative_tuple[i] + tup[i] for i in range(len(tup)))
rest_of_list = accumulative_sum(tuples, index+1, new_tup)
return [new_tup] + rest_of_list
test_list = [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
res=accumulative_sum(test_list)
print("Accumulative index summation of tuple list : " + str(res))
OutputAccumulative index summation of tuple list : [(3, 4, 5), (7, 9, 12), (8, 13, 22)]
Time complexity: O(n), where n is the number of tuples in the list. This is because the algorithm needs to process each tuple in the list once.
Auxiliary space: O(n), because the space used by the algorithm depends on the size of the input list. The algorithm creates a new list to store the result, which can have at most n tuples. Additionally, the algorithm uses a constant amount of space to store loop variables and temporary tuples.
Method 7: Using reduce() function from functools module
- Import reduce() function from the functools module.
- Define a lambda function that adds the tuples element-wise.
- Use reduce() function to calculate the cumulative sum of the tuples in the list.
- Store the cumulative sum in a new list of tuples.
Python3
from functools import reduce
def accumulative_sum(tuples):
return reduce(lambda acc, curr: acc + [tuple(map(sum, zip(curr, acc[-1])))], tuples[1:], [tuples[0]])
test_list = [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
res = accumulative_sum(test_list)
print("Accumulative index summation of tuple list : " + str(res))
OutputAccumulative index summation of tuple list : [(3, 4, 5), (7, 9, 12), (8, 13, 22)]
Time complexity: O(n^2), since the reduce() function iterates over the tuples in the list once for each tuple.
Auxiliary space: O(n), since we are creating a new list of tuples to store the cumulative sum.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read