How to usethe built-in function reduce() from the functools module. in Python
Step-by-step approach:
- The reduce() function from the functools module is used to apply a function to each tuple in the list, accumulating the sum of the k-th element so far.
- The function passed to reduce() takes two arguments: acc, which is the accumulated sum so far, and tpl, which is the current tuple being processed.
- The lambda function returns the sum of the accumulated sum so far (acc) and the k-th element of the current tuple (tpl[k]).
- The reduce() function starts with an initial value of 0 for the accumulated sum.
- The test_list variable initializes a list of tuples that will be used to test the sum_kth_column_reduce function.
- The K variable initializes the value of the index of the column to sum.
- The res variable initializes the sum to zero using the sum_kth_column_reduce function with test_list and K as arguments.
- The print() function is used to output the original list of tuples and the sum of the k-th column.
Below is the implementation of the above approach:
Python3
import functools def sum_kth_column_reduce(tuples_list, k): return functools. reduce ( lambda acc, tpl: acc + tpl[k], tuples_list, 0 ) # initialize the list of tuples test_list = [( 5 , 6 , 7 ), ( 1 , 3 , 5 ), ( 8 , 9 , 19 )] # initialize the value of K K = 2 # initialize the sum to zero res = sum_kth_column_reduce(test_list, K) # print the original list print ( "The original list is : " + str (test_list)) # print the result print ( "Summation of Kth Column of Tuple List : " + str (res)) |
Output
The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)] Summation of Kth Column of Tuple List : 31
Time complexity: O(n), where n is the length of the input tuples_list.
Auxiliary space: O(1), as the program only uses a constant amount of additional memory, regardless of the size of the input.
Python | Summation of Kth Column of Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let’s discuss certain ways in which this task can be performed.