Nowadays, especially in the field of competitive programming, the utility of computing suffix sum is quite popular and features in many problems. Hence, having a one-liner solution to it would possess a great help. Let’s discuss the certain way in which this problem can be solved.
Method 1: Using list comprehension + sum() + list slicing
This problem can be solved using the combination of above two functions in which we use list comprehension to extend the logic to each element, sum function to get the sum along, slicing is used to get sum till the particular index.
Python3
# Python3 code to demonstrate
# Suffix List Sum
# using list comprehension + sum() + list slicing
# initializing list
test_list = [3, 4, 1, 7, 9, 1]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + sum() + list slicing
# Suffix List Sum
test_list.reverse()
res = [sum(test_list[: i + 1]) for i in range(len(test_list))]
# print result
print("The suffix sum list is : " + str(res))
Output : The original list : [3, 4, 1, 7, 9, 1]
The suffix sum list is : [1, 10, 17, 18, 22, 25]
Time complexity: O(n^2), where n is the length of the input list.
Auxiliary space: O(n) The program uses a list of length n to store the suffix sums.
Method#2: Using a for loop
Python3
def suffix_sum(lst):
result = []
sum = 0
for i in range(len(lst) - 1, -1, -1):
sum += lst[i]
result.append(sum)
return result
# input sample list
test_list = [3, 4, 1, 7, 9, 1]
print("The original list :", test_list)
res = suffix_sum(test_list)
# printing list
print("The suffix sum list is :", res)
OutputThe original list : [3, 4, 1, 7, 9, 1]
The suffix sum list is : [1, 10, 17, 18, 22, 25]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#3: Using the Recursive method
Python3
def suffix_sum_recursive(lst, sum=0, result=None):
if result is None:
result = []
if len(lst) == 0:
return result
sum += lst[-1]
result.append(sum)
return suffix_sum_recursive(lst[:-1], sum, result)
# input sample list
test_list = [3, 4, 1, 7, 9, 1]
print("The original list :", test_list)
res = suffix_sum_recursive(test_list)
# printing the list
print("The suffix sum list is :", res)
OutputThe original list : [3, 4, 1, 7, 9, 1]
The suffix sum list is : [1, 10, 17, 18, 22, 25]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#4: Using itertools.accumulate() function:
Algorithm:
- Reverse the original list.
- Compute the cumulative sum of the reversed list using itertools.accumulate() function.
- Reverse the cumulative sum list to get the final suffix sum list.
Python3
from itertools import accumulate
test_list = [3, 4, 1, 7, 9, 1]
# printing original list
print("The original list : " + str(test_list))
suffix_sum = list(accumulate(reversed(test_list)))
# printing the list
print("The suffix sum list is:", suffix_sum)
OutputThe original list : [3, 4, 1, 7, 9, 1]
The suffix sum list is: [1, 10, 17, 18, 22, 25]
Time Complexity:
The time complexity of this algorithm is O(n), where n is the length of the input list. The itertools.accumulate() function takes O(n) time to compute the cumulative sum, and the reverse operation takes O(n) time as well.
Auxiliary Space:
The space complexity of this algorithm is also O(n), where n is the length of the input list. The itertools.accumulate() function creates a generator object that stores the intermediate values of the cumulative sum, which takes O(n) space. The final suffix sum list also takes O(n) space.
Method 5: using a generator expression and the reversed() function:
Steps:
- Define a function suffix_sum_generator() that takes a list lst as input.
- Initialize an empty list suffix_sum to store the suffix sums.
- Create a generator expression using a for loop and the sum() function to calculate the suffix sum for each suffix of the list. The generator expression yields the suffix sums in reverse order.
- Convert the generator expression to a list and reverse it using the reversed() function to get the suffix sums in the correct order.
- Append each suffix sum to the suffix_sum list.
- Return the suffix_sum list.
Python3
def suffix_sum_generator(lst):
suffix_sum = []
suffix_sum_gen = (sum(lst[i:]) for i in range(len(lst)))
for num in reversed(list(suffix_sum_gen)):
suffix_sum.append(num)
return suffix_sum
# Sample input
test_list = [3, 4, 1, 7, 9, 1]
print("The original list :", test_list)
# Call suffix_sum_generator() function
res = suffix_sum_generator(test_list)
# printing list
print("The suffix sum list is :", res)
OutputThe original list : [3, 4, 1, 7, 9, 1]
The suffix sum list is : [1, 10, 17, 18, 22, 25]
Time complexity: O(n^2)
Auxiliary space: O(n)
Method 6: Using numpy.cumsum() function
Step-by-step algorithm:
- Initialize an empty list suffix_sum.
- Initialize a variable total to 0.
- Loop through the input list test_list in reverse order using the reversed() function:
- Add the current element to total.
- Append total to the suffix_sum list.
- Reverse the suffix_sum list using the reverse() method.
- Return the suffix_sum list.
Python3
# import numpy library
import numpy as np
# initialize list
test_list = [3, 4, 1, 7, 9, 1]
# reverse the list using slicing and compute the cumulative sum using numpy.cumsum()
# then reverse the result again to obtain the correct order of suffix sum values
suffix_sum = np.cumsum(test_list[::-1])[::-1].tolist()
# create a list of indices in descending order
index_list = list(range(len(test_list)-1, -1, -1))
# use the index list to access the suffix sum values in the correct order
suffix_sum_ordered = [suffix_sum[i] for i in index_list]
# print the ordered suffix sum list and the index list
print("Index list:", index_list)
print("Ordered suffix sum list:", suffix_sum_ordered)
output
Index list: [5, 4, 3, 2, 1, 0]
Ordered suffix sum list: [1, 10, 17, 18, 22, 25]
Time complexity:
The time complexity of this approach is O(n), where n is the length of the input list test_list. This is because we loop through the list once, and perform constant time operations inside the loop.
Auxiliary space complexity:
The auxiliary space complexity of this approach is O(n), where n is the length of the input list test_list. This is because we create a new list suffix_sum to store the suffix sum values, which requires n elements of space. Additionally, we use a constant amount of space for the total and loop variables.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read