Friday, November 15, 2024
Google search engine
HomeLanguagesPython – Multiply Consecutive elements in list

Python – Multiply Consecutive elements in list

While working with python, we usually come by many problems that we need to solve in day-day and in development. Specially in development, small tasks of python are desired to be performed in just one line. We discuss some ways to compute a list consisting of elements that are successive product in the list. 

Method #1 : Using list comprehension Naive method can be used to perform, but as this article discusses the one liner solutions to this particular problem, we start with the list comprehension as a method to perform this task. 

Python3




# Python3 code to demonstrate
# Consecutive Product list
# using list comprehension
 
# initializing list
test_list = [1, 4, 5, 3, 6]
 
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using list comprehension
# Consecutive Product list
res = [test_list[i] * test_list[i + 1] for i in range(len(test_list)-1)]
 
# printing result
print ("The computed successive product list is : " + str(res))


Output : 

The original list is : [1, 4, 5, 3, 6]
The computed successive product list is : [4, 20, 15, 18]

Time complexity: O(n) where n is the length of the input list.
Auxiliary space: O(n) where n is the length of the input list

Method #2 : Using zip() zip() can also be used to perform the similar task and uses the power of negative indices to zip() the index element with its next element and hence compute the product. 

Python3




# Python3 code to demonstrate
# Consecutive Product list
# using zip()
 
# initializing list
test_list = [1, 4, 5, 3, 6]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using zip()
# Consecutive Product list
res = [i * j for i, j in zip(test_list[: -1], test_list[1 :])]
 
# printing result
print ("The computed successive product list is : " + str(res))


Output : 

The original list is : [1, 4, 5, 3, 6]
The computed successive product list is : [4, 20, 15, 18]

Time complexity: O(n), where n is the length of the input list, since we are iterating through the list once to create the successive product list.
Auxiliary space: O(n), since we are creating a new list to store the successive product list. The size of this new list will be n-1, since there are only n-1 consecutive pairs in the input list.

Method#3: Using Recursive method.

Python3




def consecutive_product(test_list, index=0):
    if index == len(test_list) - 1:
        return []
    return [test_list[index] * test_list[index + 1]] + consecutive_product(test_list, index + 1)
 
# initializing list
test_list = [1, 4, 5, 3, 6]
 
# printing original list
print("The original list is:", test_list)
 
result = consecutive_product(test_list)
 
# printing result
print("The computed successive product list is:", result)
#this code contributed by tvsk


Output

The original list is: [1, 4, 5, 3, 6]
The computed successive product list is: [4, 20, 15, 18]

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

Method#4:Using enumeration

Algorithm:

  1. Initialize an empty list called res to store the computed successive product.
  2. Iterate over the list using the enumerate() function, which provides the current index and its corresponding value in each iteration.
  3. For each index except the last, multiply the current element with the next element, and append the result to the res list.
  4. Return the res list.
     

Python3




# Python3 code to demonstrate
# Consecutive Product list
# using list comprehension and enumerate()
 
# initializing list
test_list = [1, 4, 5, 3, 6]
 
# printing original list
print("The original list is : ", test_list)
 
# using list comprehension and enumerate()
# Consecutive Product list
res = [test_list[i] * val for i, val in enumerate(test_list[1:])]
 
# printing result
print("The computed successive product list is : ", res)
#This code is contributed by Vinay Pinjala.


Output

The original list is :  [1, 4, 5, 3, 6]
The computed successive product list is :  [4, 20, 15, 18]

Time Complexity: O(n), where n is the length of the input list. This is because the algorithm iterates over the input list only once to compute the successive product.

Auxiliary Space: O(n), where n is the length of the input list. This is because the algorithm stores the computed successive product in a list of size n-1.

Method #5: Using a for loop

  1. Initialize an empty list named “res”.
  2. Iterate over the indices of the input list “test_list” from 0 to the second last index.
  3. For each index i, multiply the i-th element of “test_list” with the (i+1)-th element of “test_list”, and append the result to the “res” list.
  4. Return the “res” list.
  5. Initialize an input list named “test_list” with some integer values.
  6. Print the original value of the input list.
  7. Call the function that implements the above approach and store the result in a variable named “res”.
  8. Print the final consecutive product list “res”.

Python3




# Python3 code to demonstrate
# Consecutive Product list
# using for loop
 
# initializing list
test_list = [1, 4, 5, 3, 6]
 
# printing original list
print("The original list is : ", test_list)
 
# using for loop
# Consecutive Product list
res = []
for i in range(len(test_list)-1):
    res.append(test_list[i] * test_list[i+1])
 
# printing result
print("The computed successive product list is : ", res)
#This code is contributed by [author's name].


Output

The original list is :  [1, 4, 5, 3, 6]
The computed successive product list is :  [4, 20, 15, 18]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list (used for storing the output list).

Method #6: Using a while loop

Step-by-step approach:

  1. Initialize two variables, i and result, to zero.
  2. Create an empty list, res.
  3. While i is less than the length of the test_list subtracted by one, repeat the following steps:
    a. Set result equal to the product of test_list[i] and test_list[i+1].
    b. Append result to the res list.
    c. Increment i by 1.
  4. Print the computed successive product list, res.

Python3




# Python3 code to demonstrate
# Consecutive Product list
# using while loop
 
# initializing list
test_list = [1, 4, 5, 3, 6]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using while loop
# Consecutive Product list
i = 0
res = []
while i < len(test_list) - 1:
    result = test_list[i] * test_list[i+1]
    res.append(result)
    i += 1
 
# printing result
print("The computed successive product list is : " + str(res))


Output

The original list is : [1, 4, 5, 3, 6]
The computed successive product list is : [4, 20, 15, 18]

Time Complexity: O(n), where n is the length of the input list test_list.

Auxiliary Space: O(n), where n is the length of the input list test_list. 

Method #7: Using heapq:

Algorithm:

  1. Initialize an empty list res.
  2. Loop through the given list test_list from index 1.
  3. Calculate the product of the current element and its previous element.
  4. Push the calculated product to the res list using heapq.heappush().
  5. Repeat steps 3-4 for all elements except the first one.
  6. The res list will now contain the computed successive product list.

Python3




import heapq
 
# initializing list
test_list = [1, 4, 5, 3, 6]
 
# printing original list
print("The original list is : ", test_list)
 
# using heapq
# Consecutive Product list
res = []
for i, val in enumerate(test_list[1:]):
    heapq.heappush(res, test_list[i] * val)
 
# printing result
print("The computed successive product list is : ", res)
#This code is contributed by Rayudu.


Output

The original list is :  [1, 4, 5, 3, 6]
The computed successive product list is :  [4, 18, 15, 20]

Time Complexity: O(nlogn), where n is the length of the given list. This is because heapq.heappush() has a time complexity of O(logn), and it is called n-1 times in the loop.

Space Complexity: O(n), where n is the length of the given list. This is because the res list stores n-1 elements. The heapq module also uses additional memory to store the heap, but it is usually not significant.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments