Open In App

Python – Alternate Elements operation on Tuple

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

Sometimes, while working with Python Tuples, we can have problem in which we need to perform operations of extracted alternate chains of tuples. This kind of operation can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed.

Input : test_tuple = (5, 6, 3) 
Output : The alternate chain sum 1 : 6 The alternate chain sum 2 : 8 

Input : test_tuple = (5, 6) 
Output : The alternate chain sum 1 : 6 The alternate chain sum 2 : 5

Method #1 : Using loop + enumerate() 

The combination of above functions provide brute force solution to this problem. In this, we extract the elements along with indices using enumerate() and perform chaining using condition. 

Python3




# Python3 code to demonstrate working of
# Alternate Elements operation on Tuple
# Using loop + enumerate()
 
# initializing tuple
test_tuple = (5, 6, 3, 6, 10, 34)
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Alternate Elements operation on Tuple
# Using loop + enumerate()
sum1 = 0
sum2 = 0
for idx, ele in enumerate(test_tuple):
    if idx % 2:
        sum1 += ele
    else:
        sum2 += ele
 
# printing result
print("The alternate chain sum 1 : " + str(sum1))
print("The alternate chain sum 2 : " + str(sum2))


Output

The original tuple : (5, 6, 3, 6, 10, 34)
The alternate chain sum 1 : 46
The alternate chain sum 2 : 18

Method #2 : Using list slicing 

This problem can also be performed using slicing operations. In this, we perform the task of extracting alternate chains using list slicing technique. 

Python3




# Python3 code to demonstrate working of
# Alternate Elements operation on Tuple
# Using list slicing
 
# initializing tuple
test_tuple = (5, 6, 3, 6, 10, 34)
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Alternate Elements operation on Tuple
# Using list slicing
sum1 = sum(test_tuple[1::2])
sum2 = sum(test_tuple[0::2])
 
# printing result
print("The alternate chain sum 1 : " + str(sum1))
print("The alternate chain sum 2 : " + str(sum2))


Output

The original tuple : (5, 6, 3, 6, 10, 34)
The alternate chain sum 1 : 46
The alternate chain sum 2 : 18

Method 3: Recursive function

Approach:

  • In the first line, we define the tuple test_tuple with the given values.
  • In the next two lines, we calculate the alternate chain sums using slicing and the sum function. The expression test_tuple[::2] returns a new tuple that contains elements at even indices (i.e., 0, 2, 4, etc.), and test_tuple[1::2] returns a new tuple that contains elements at odd indices (i.e., 1, 3, 5, etc.). Then we simply pass these tuples to the sum function to calculate their sums.
  • Finally, we print the results using the print function.

Python3




def remove_nested_none(d):
    for k, v in d.items():
        if isinstance(v, dict):
            remove_nested_none(v)
        elif v is None:
            del d[k]
    return d
 
 
test_tuple = (5, 6, 3, 6, 10, 34)
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
alt_sum_2 = sum(test_tuple[1::2])  # sum of elements at odd indices
alt_sum_1 = sum(test_tuple[::2])  # sum of elements at even indices
 
print("The alternate chain sum 1 :", alt_sum_1)
print("The alternate chain sum 2 :", alt_sum_2)


Output

The original tuple : (5, 6, 3, 6, 10, 34)
The alternate chain sum 1 : 18
The alternate chain sum 2 : 46

Time complexity: O(n), where n is the number of values in the dictionary
 Space complexity: O(h), where h is the maximum depth of nested dictionaries

Method 4:  using list comprehension

Step-by-step approach:

  1. Define a tuple test_tuple containing six integers: (5, 6, 3, 6, 10, 34).
  2. Use list comprehension to create a new list containing the elements of test_tuple at even indices. The list comprehension uses the range() function with a step of 2 to iterate over the even indices, and accesses the elements of test_tuple at those indices. The resulting list is passed to the sum() function to calculate the sum of its elements, and the result is assigned to the variable alt_sum_1.
  3. Use list comprehension again to create a new list containing the elements of test_tuple at odd indices.
  4. The list comprehension uses the range() function with a starting index of 1 and a step of 2 to iterate over the odd indices, and accesses the elements of test_tuple at those indices. The resulting list is passed to the sum() function to calculate the sum of its elements, and the result is assigned to the variable alt_sum_2.
  5. Print the values of alt_sum_1 and alt_sum_2.

Python3




test_tuple = (5, 6, 3, 6, 10, 34)
alt_sum_1 = sum([test_tuple[i] for i in range(0, len(test_tuple), 2)])
alt_sum_2 = sum([test_tuple[i] for i in range(1, len(test_tuple), 2)])
print("The alternate chain sum 1 :", alt_sum_1)
print("The alternate chain sum 2 :", alt_sum_2)


Output

The alternate chain sum 1 : 18
The alternate chain sum 2 : 46

Time complexity: O(N), where N is the length of the tuple. We need to iterate over the entire tuple once to calculate the sums.
Auxiliary space: O(N), where N is the length of the tuple. We are creating two lists using list comprehension, each of size N/2 (rounded up), to store the elements at even and odd indices.



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

Similar Reads