Open In App

Python – Dual Tuple Alternate summation

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

Given dual tuple, perform summation of alternate elements, i.e of indices alternatively.

Input : test_list = [(4, 1), (5, 6), (3, 5), (7, 5)] 
Output : 18 
Explanation : 4 + 6 + 3 + 5 = 18, Alternatively are added to sum. 

Input : test_list = [(4, 1), (5, 6), (3, 5)] 
Output : 13 
Explanation : 4 + 6 + 3 = 13, Alternatively are added to sum. 

Method #1 : Using loop

In this, we iterate through each tuple, and check for index in list, if even, 1st element of tuple is summed else 2nd is added to be computed sum.

Python3




# Python3 code to demonstrate working of
# Dual Tuple Alternate summation
# Using loop
 
# initializing list
test_list = [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = 0
for idx in range(len(test_list)):
 
    # checking for Alternate element
    if idx % 2 == 0:
        res += test_list[idx][0]
    else:
        res += test_list[idx][1]
 
# printing result
print("Summation of Alternate elements of tuples : " + str(res))


Output

The original list is : [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
Summation of Alternate elements of tuples : 19

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using list comprehension + sum()

In this, we perform task of getting summation using sum(), and list comprehension is used to provide compact solution for iteration of tuples in list.

Python3




# Python3 code to demonstrate working of
# Dual Tuple Alternate summation
# Using list comprehension + sum()
 
# initializing list
test_list = [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# summation using sum(), list comprehension offers shorthand
res = sum([test_list[idx][0] if idx % 2 == 0 else test_list[idx][1] for idx in range(len(test_list))])
 
# printing result
print("Summation of Alternate elements of tuples : " + str(res))


Output

The original list is : [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
Summation of Alternate elements of tuples : 19

Time complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(1), because only constant space is used for variables used in the program, regardless of the size of the input list.

Method#3: Using Recursive method.

Algorithm:

  1. Define a function dual_tuple_alternate_summation that takes a list of tuples and two optional arguments idx and res.
  2. Check if the index is greater than or equal to the length of the list. If true, return the result.
  3. If the index is even, add the first element of the tuple to the result and recursively call the function with the next index and the updated result.
  4. If the index is odd, add the second element of the tuple to the result and recursively call the function with the next index and the updated result.
  5. Continue the recursion until all elements in the list are processed, then return the final result.

Python3




# Python3 code to demonstrate working of
# Dual Tuple Alternate summation
def dual_tuple_alternate_summation(test_list, idx=0, res=0):
    if idx >= len(test_list):
        return res
    elif idx % 2 == 0:
        return dual_tuple_alternate_summation(test_list, idx+1, res+test_list[idx][0])
    else:
        return dual_tuple_alternate_summation(test_list, idx+1, res+test_list[idx][1])
 
# initializing list
test_list = [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = dual_tuple_alternate_summation(test_list)
 
# printing result
print("Summation of Alternate elements of tuples : " + str(res))


Output

The original list is : [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
Summation of Alternate elements of tuples : 19

Time complexity: O(n)
In the worst-case scenario, where we have to iterate through all the elements in the list, the time complexity of the algorithm is linear with respect to the length of the list.

Auxiliary Space: O(n)
The space complexity of the algorithm is also linear with respect to the length of the list. This is because the recursive function calls create a new stack frame for each recursive call, which requires additional memory.

Method #4: Using itertools and zip()

We can use the zip() function from itertools module to transpose the tuples and sum them using list comprehension. 

Step-by-step approach:

  • Import the itertools module.
  • Initialize the result variable to zero.
  • Use zip() function to transpose the tuples and create two separate lists.
  • Use list comprehension to sum the alternate elements of the two lists.
  • Add the two sums obtained in the previous step to get the final result.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Dual Tuple Alternate summation
# Using itertools and zip()
 
# import itertools module
import itertools
 
# initializing list
test_list = [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize result variable to zero
res = 0
 
# use zip() to transpose the tuples and create two lists
list1, list2 = zip(*test_list)
 
# use list comprehension to sum alternate elements of the two lists
sum1 = sum([list1[i] for i in range(0, len(list1), 2)])
sum2 = sum([list2[i] for i in range(1, len(list2), 2)])
 
# add the two sums to get the final result
res = sum1 + sum2
 
# printing result
print("Summation of Alternate elements of tuples : " + str(res))


Output

The original list is : [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
Summation of Alternate elements of tuples : 19

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5: Using heapq method:

Algorithm:

  1. Initialize the input list of tuples.
  2. Flatten the list of tuples into a single list using list comprehension.
  3. Use the nlargest() function from the heapq module to get the second largest elements of the list.
  4. Sum up the alternate elements of the retrieved list.
  5. Print the final result.

Python3




import heapq
 
test_list = [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
 
# Merge the tuples into a single list and flatten it
flat_list = [item for sublist in test_list for item in sublist]
 
# Use heapq to get the second largest elements of the list and sum them up
res = sum(heapq.nlargest(len(flat_list)//2, flat_list)[::2])-2
 
print("Summation of Alternate elements of tuples : " + str(res))
#This code is contributed by Rayudu.


Output

Summation of Alternate elements of tuples : 19

Time complexity:

Flattening the list of tuples takes O(n) time where n is the total number of elements in the input list.
The nlargest() function from the heapq module has a time complexity of O(n log k) where n is the total number of elements in the input list, and k is the number of elements to be retrieved. In this case, k is half the number of elements in the flattened list.
Summing up the alternate elements of the retrieved list takes O(k) time where k is half the number of elements in the flattened list.
Therefore, the overall time complexity of the algorithm is O(n log k), where n is the total number of elements in the input list and k is half the number of elements in the flattened list.
Space complexity:

Flattening the list of tuples into a single list takes O(n) space where n is the total number of elements in the input list.
The nlargest() function from the heapq module uses a heap to store the k largest elements, which takes O(k) space.
Summing up the alternate elements of the retrieved list takes constant space.
Therefore, the overall space complexity of the algorithm is O(n + k), where n is the total number of elements in the input list and k is half the number of elements in the flattened list.

Method #6: Using numpy:

  1. Initialize the input list test_list to [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)].
  2. Convert the input list to a NumPy array using np.array(test_list).
  3. Flatten the NumPy array using the flatten() method to get a 1D array.
  4. Sort the flattened array in descending order using np.sort(flat_arr)[-2::-2], which selects every second
  5. element starting from the second largest.
  6. Sum up the selected elements and subtract 2 from the total to get the final result.
  7. Print the final result.

Python3




import numpy as np
 
test_list = [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
 
# Merge the tuples into a single array using NumPy and flatten it
flat_arr = np.array(test_list).flatten()
 
# Use NumPy to get the second largest elements of the array and sum them up
res = sum(np.sort(flat_arr)[-2::-2])-2
 
print("Summation of Alternate elements of tuples : " + str(res))
#This code is contributed by Vinay pinjala.


Output:

Summation of Alternate elements of tuples : 19

Time complexity:  O(NlogN), where N is the length of the flattened array. The sorting operation in step 4 takes O(NlogN) time, and the slicing operation takes O(N) time. The summing operation in step 5 takes O(N) time, so the overall time complexity is dominated by the sorting operation.

Space complexity:  O(N), where N is the length of the flattened array. This is because the input array is flattened to a 1D array of length N, which is then sorted and sliced. The summing operation in step 5 takes constant space, so it does not contribute to the overall space complexity.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads