Q:

Python program to multiply adjacent elements of a tuple

belongs to collection: Python Tuple Programs

0

Example:

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

Multiplying adjacent elements of a tuple

In this problem, we are given a tuple with integer elements. In our program, we need to create a tuple from the elements of the initial tuple where each tuple is the product of the element at that index and next index.

Input:
(5, 1, 8, 3, 7)

Output:
(5, 8, 24, 21)

To perform this task we will iterate the first tuple and find the product of the current element and its next. This can be done in multiple ways in Python.

All Answers

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

Method 1:

One method to solve the problem is by zipping the current element and the next one for each element of the tuple. Then using the generator expression along with tuple method to create a tuple with the resulting values.

# Python program to multiply adjacent 
# elements of a tuple

# Initializing and printing tuple value
myTup = (5, 1, 8, 3, 7)
print("The elements of tuple : " + str(myTup))

# Multiplying adjacent elements of the tuple 
adjProd = tuple(val1 * val2 for val1, val2 in zip(myTup, myTup[1:]))
print("The multiplication values are " + str(adjProd))

Output:

The elements of tuple : (5, 1, 8, 3, 7)
The multiplication values are (5, 8, 24, 21)

Method 2:

Another method to solve the problem is by creating a map that uses a lambda function to multiply the current index element and the next index element of the tuple and then convert this map to a tuple.

# Python program to multiply adjacent 
# elements of a tuple

# Initializing and printing tuple value
myTup = (5, 1, 8, 3, 7)
print("The elements of tuple : " + str(myTup))

# Multiplying adjacent elements of the tuple 
adjProd = tuple(map(lambda val1, val2 : val1 * val2, myTup[1:], myTup[:-1]))

print("The multiplication values are " + str(adjProd))

Output:

The elements of tuple : (5, 1, 8, 3, 7)
The multiplication values are (5, 8, 24, 21)

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 extract unique elements in neste... >>
<< Python program to update each element in the tuple...