Q:

Python program to perform pairwise addition in tuples

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Pairwise Addition in Tuples

We are given a tuple of integer elements. We need to create a python program to make pairs of adjacent elements of each tuple and then perform pairwise addition operations on these tuples.

Input:
(3, 1, 7, 9, 2) 

Output:
(4, 8, 16, 11)

To perform the pairwise addition operation, we will iterate over the tuple then for each element return the number of pairs of current elements and the element next to it. Let's see different implementations of this concept in python.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

In this method, we will return the sum of pairs of an element of the tuple and the element next to it. The pair sum is done using a generator function and the pairing of neighbouring elements is done using zip() method. All these pair sum values are added to a tuple which is our result.

# Python program to perform pairwise 
# addition in tuples
  
# Initializing and printing tuple 
myTuple = (3, 1, 7, 9, 2)
print("The elements of tuple are " + str(myTuple))
  
# Performing pairwise addition operation on tuples
additionTuple = tuple(i + j for i, j in zip(myTuple, myTuple[1:]))
  
# Printing result 
print("The pairwise added elements in tuple are " + str(additionTuple))

Output:

The elements of tuple are (3, 1, 7, 9, 2)
The pairwise added elements in tuple are (4, 8, 16, 11)

Method 2:

One more implementation of the solution is by using the create a map where each element is created using a lambda function which will take the sum of the current and next element of the sum. Then the map with additional pairs is then converted using tuple().

# Initializing and printing tuple 
myTuple = (3, 1, 7, 9, 2)
print("The elements of tuple are " + str(myTuple))
  
# Performing pairwise addition operation on tuples
additionTuple = tuple(map(lambda i, j : i + j, myTuple[1:], myTuple[:-1]))
  
# Printing result 
print("The pairwise added elements in tuple are " + str(additionTuple))

Output:

The elements of tuple are (3, 1, 7, 9, 2)
The pairwise added elements in tuple are (4, 8, 16, 11)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to perform concatenation of two str... >>
<< Python program to find the modulo of tuple element...