Python | Alternate front - rear Sum
Last Updated :
17 Apr, 2023
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 alternate front-rear sum in the list.
Method #1: Using loop
This is brute force method in which this problem can be solved. In this, we take two pointers and store their sum in array while increasing and decreasing their positions.
Python3
# Python3 code to demonstrate
# Alternate front - rear Sum
# using loop
# initializing list
test_list = [1, 4, 5, 3, 6, 7]
# printing original list
print ("The original list is : " + str(test_list))
# Alternate front - rear Sum
# using loop
res = []
j = len(test_list) - 1
for i in range(0, len(test_list) // 2):
res.append(test_list[i] + test_list[j])
j = j - 1
# printing result
print ("The alternate front - rear Sum list is : " + str(res))
OutputThe original list is : [1, 4, 5, 3, 6, 7]
The alternate front - rear Sum list is : [8, 10, 8]
Time complexity: O(n/2) = O(n) - as the loop runs through half of the length of the list.
Auxiliary space: O(n) - as an empty list (res) is used to store the result, which has the same length as the input list.
Method #2: Using list comprehension
Naive method can be used to perform, but list comprehension provides a one liner method to perform this task.
Python3
# Python3 code to demonstrate
# Alternate front - rear Sum
# using list comprehension
# initializing list
test_list = [1, 4, 5, 3, 6, 7]
# printing original list
print ("The original list is : " + str(test_list))
# Alternate front - rear Sum
# using list comprehension
res = [test_list[i] + test_list[len(test_list) - (i + 1)] for i in range(len(test_list) // 2)]
# printing result
print ("The alternate front - rear Sum list is : " + str(res))
OutputThe original list is : [1, 4, 5, 3, 6, 7]
The alternate front - rear Sum list is : [8, 10, 8]
Time complexity: O(n/2) = O(n) - as the loop runs through half of the length of the list.
Auxiliary space: O(n) - as an empty list (res) is used to store the result, which has the same length as the input list.
Method #3: Using zip() and slicing
Python3
# Python3 code to demonstrate
# Alternate front - rear Sum
# using zip() and slicing
# initializing list
test_list = [1, 4, 5, 3, 6, 7]
# printing original list
print ("The original list is : " + str(test_list))
# Alternate front - rear Sum
# using zip() and slicing
res = [x+y for x, y in zip(test_list[:len(test_list)//2], test_list[-1:-(len(test_list)//2)-1:-1])]
# printing result
print ("The alternate front - rear Sum list is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list is : [1, 4, 5, 3, 6, 7]
The alternate front - rear Sum list is : [8, 10, 8]
This method uses the zip function to combine elements from the front and rear of the list, and slicing to select the appropriate number of elements from each end. This method has the advantage of being more readable and easier to understand than the previous two methods. The time and space complexity would be O(n) similar to the previous two methods.
Method #4: Using map() and lambda():
Python3
test_list = [1, 4, 5, 3, 6, 7]
result = list(map(lambda i,j: i+j, test_list[:len(test_list)//2], test_list[-1:len(test_list)//2-1:-1]))
print(result)
#This code is contributed by pinjala Jyothi
Time complexity : O(n)
Auxiliary Space : O(n)
Method#5: using itertools
Python3
import itertools
test_list = [1, 4, 5, 3, 6, 7]
res = [x+y for x,y in itertools.zip_longest(test_list[:len(test_list)//2], test_list[-1:len(test_list)//2-1:-1]) if x is not None and y is not None]
print(res)
#This code is contributed by Vinay Pinjala
Method #6: Using a for loop with two pointers.
This method involves using two pointers, one pointing to the front of the list and the other pointing to the rear of the list. The sum of the values pointed by these two pointers is calculated and stored in the result list. Then, the pointers are moved towards each other until they meet at the middle of the list.
STEPS:
- Initialize a list named test_list with some integer values.
- Print the original list using the print() function.
- Initialize an empty list named res to store the alternate front-rear sum.
- Initialize two pointers, start and end, to the first and last indices of the test_list respectively.
- Use a while loop to iterate until start is less than end.
- In each iteration of the loop, append the sum of the values at the start and end indices of the test_list to the res list.
- Increment the start pointer by 1 and decrement the end pointer by 1.
- After the loop finishes executing, print the alternate front-rear sum list using the print() function
Python3
# Python3 code to demonstrate
# Alternate front - rear Sum
# using a for loop with two pointers
# initializing list
test_list = [1, 4, 5, 3, 6, 7]
# printing original list
print ("The original list is : " + str(test_list))
# Alternate front - rear Sum
# using a for loop with two pointers
res = []
start = 0
end = len(test_list) - 1
while start < end:
res.append(test_list[start] + test_list[end])
start += 1
end -= 1
# printing result
print ("The alternate front - rear Sum list is : " + str(res))
OutputThe original list is : [1, 4, 5, 3, 6, 7]
The alternate front - rear Sum list is : [8, 10, 8]
Time complexity: O(n), where n is the length of the list
Auxiliary space: O(n), where n is the length of the list (for the result list)
Method#7: Using Recursive method.
Algorithm:
- Define a function named alt_front_rear_sum that takes a list as an input.
- Check the length of the list, if it is zero, then return an empty list.
- If the length of the list is not zero, then make a recursive call to the function with the list sliced from the second element to the second to last element.
- Calculate the front-rear sum and append it to the result list. If the length of the list is even, then insert it at the beginning of the result list, otherwise append it at the end of the result list.
- Return the result list.
- Print the original list and the result list.
Python3
# Python3 code to demonstrate
# Alternate front - rear Sum
# using loop
def alt_front_rear_sum(test_list):
# base case
if len(test_list) == 0:
return []
# recursive call
res = alt_front_rear_sum(test_list[1:-1])
# calculating front-rear sum
if len(test_list) % 2 == 0:
res.insert(0, test_list[0] + test_list[-1])
else:
res.append(test_list[0] + test_list[-1])
return res
# initializing list
test_list = [1, 4, 5, 3, 6, 7]
# printing original list
print ("The original list is : " + str(test_list))
# Alternate front - rear Sum
# using loop
res = alt_front_rear_sum(test_list)
# printing result
print ("The alternate front - rear Sum list is : " + str(res))
OutputThe original list is : [1, 4, 5, 3, 6, 7]
The alternate front - rear Sum list is : [8, 10, 8]
Time complexity: O(n), where n is the length of the input list. The algorithm involves a single traversal of the input list, and the recursive call is made for a list of size n-2, so the time complexity can be expressed as T(n) = T(n-2) + O(1).
Auxiliary Space: O(n), where n is the length of the input list. This is because the algorithm creates a result list of size n/2 (rounded up) to store the front-rear sums, and the recursive call is made for a list of size n-2, so the space complexity can be expressed as S(n) = S(n-2) + O(n/2).
Similar Reads
Python | Alternate Rear iteration
The iteration of numbers is done by looping techniques in python. There are many techniques in Python which facilitate looping. Sometimes we require to perform the looping backwards in alternate way and having shorthands to do so can be quite useful. Letâs discuss certain ways in which this can be d
3 min read
Python | Alternate element summation in list
The problem of getting summation of a list is quite generic and we might some day face the issue of getting the summation of alternate elements and get the list of 2 elements containing summation of alternate elements. Let's discuss certain ways in which this can be performed. Method #1 : Using list
5 min read
Python - Summation after elements removal
Sometimes we need to perform the operation of removing all the items from the lists that are present in other list, i.e we are given some of the invalid numbers in one list which needs to be get ridden from the original list and perform its summation. Lets discuss various ways in which this can be p
5 min read
Python | Strings with similar front and rear character
Sometimes, while programming, we can have a problem in which we need to check for the front and rear characters of each string. We may require to extract the count of all strings with similar front and rear characters. Let's discuss certain ways in which this task can be performed. Method #1: Using
4 min read
Python - Dual Tuple Alternate summation
Given dual tuple, perform summation of alternate elements, i.e of indices alternatively. Input : test_list = [(4, 1), (5, 6), (3, 5), (7, 5)] Output : 18 Explanation : 4 + 6 + 3 + 5 = 18, Alternatively are added to sum. Input : test_list = [(4, 1), (5, 6), (3, 5)] Output : 13 Explanation : 4 + 6 + 3
8 min read
Python - Summation in Dual element Records List
Sometimes, while working with Records list, we can have problem in which we perform the summation of dual tuple records and store it in list. This kind of application can occur over various domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehension T
8 min read
Prefix sum list-Python
The task of creating a prefix sum list in Python involves iterating over a sequence of numbers and calculating the cumulative sum at each index. For example, with a list of numbers a = [3, 4, 1, 7, 9, 1], the task is to compute the cumulative sum at each index, resulting in a prefix sum list like [3
3 min read
Shift from Front to Rear in List - Python
The task of shifting the first element to the rear in a list in Python involves moving the first element of the list to the end while maintaining the order of the remaining elements. For example, given the list a = [1, 4, 5, 6, 7, 8, 9, 12], the goal is to produce [4, 5, 6, 7, 8, 9, 12, 1].Using col
3 min read
Python - Rear elements Average in List
Sometimes, while working with data, we can have a problem in which we need to perform the mean of all the rear elements that come after K. This can be an application in Mathematics and Data Science domain. Let us discuss certain ways in which this task can be performed. Method #1 : Using sum() + li
6 min read
Python | Sum of squares in list
Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding sum of squares of list in just one line. Let's discuss
5 min read