Python program for sum of consecutive numbers with overlapping in lists
Last Updated :
02 May, 2023
Given a List, perform summation of consecutive elements, by overlapping.
Input : test_list = [4, 7, 3, 2]
Output : [11, 10, 5, 6]
Explanation : 4 + 7 = 11, 7 + 3 = 10, 3 + 2 = 5, and 2 + 4 = 6.
Input : test_list = [4, 7, 3]
Output : [11, 10, 7]
Explanation : 4+7=11, 7+3=10, 3+4=7.
Method 1 : Using list comprehension + zip()
In this, we zip list, with consecutive elements’ using zip() and then perform summation using + operator. The iteration part is done using list comprehension.
Python3
test_list = [ 4 , 7 , 3 , 2 , 9 , 2 , 1 ]
print ( "The original list is : " + str (test_list))
res = [a + b for a, b in zip (test_list, test_list[ 1 :] + [test_list[ 0 ]])]
print ( "The Consecutive overlapping Summation : " + str (res))
|
Output
The original list is : [4, 7, 3, 2, 9, 2, 1]
The Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1) additional space is not needed.
Method #2 : Using sum() + list comprehension + zip()
In this, we perform the task of getting summation using sum() and rest all functionalities kept similar to the above method.
Python3
test_list = [ 4 , 7 , 3 , 2 , 9 , 2 , 1 ]
print ( "The original list is : " + str (test_list))
res = [ sum (sub) for sub in zip (test_list, test_list[ 1 :] + [test_list[ 0 ]])]
print ( "The Consecutive overlapping Summation : " + str (res))
|
Output
The original list is : [4, 7, 3, 2, 9, 2, 1]
The Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]
Method 3 : using a for loop
Python3
test_list = [ 4 , 7 , 3 , 2 , 9 , 2 , 1 ]
print ( "The original list is : " + str (test_list))
n = len (test_list)
res = [test_list[i] + test_list[(i + 1 ) % n] for i in range (n)]
print ( "The Consecutive overlapping Summation : " + str (res))
|
Output
The original list is : [4, 7, 3, 2, 9, 2, 1]
The Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]
The time complexity of this approach is O(n), where n is the length of the list, since we iterate over the list once.
The auxiliary space complexity is also O(n), since we need to store the result list.
Share your thoughts in the comments
Please Login to comment...