Python – Sum of Cubes in List
Last Updated :
22 Mar, 2023
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 cubes of list in just one line. Let’s discuss certain ways in which this can be performed.
Method #1 : Using reduce() + lambda The power of lambda functions to perform lengthy tasks in just one line, allows it combined with reduce which is used to accumulate the subproblem, to perform this task as well. Works with only Python 2.
Python
test_list = [ 3 , 5 , 7 , 9 , 11 ]
print ( "The original list is : " + str (test_list))
res = reduce ( lambda i, j: i + j * j * j, [test_list[: 1 ][ 0 ] * * 3 ] + test_list[ 1 :])
print ( "The sum of cubes of list is : " + str (res))
|
Output
The original list is : [3, 5, 7, 9, 11]
The sum of cubes of list is : 2555
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using map() + sum() The similar solution can also be obtained using the map function to integrate and sum function to perform the summation of the cube number.
Python3
test_list = [ 3 , 5 , 7 , 9 , 11 ]
print ( "The original list is : " + str (test_list))
res = sum ( map ( lambda i : i * i * i, test_list))
print ( "The sum of cubes of list is : " + str (res))
|
Output
The original list is : [3, 5, 7, 9, 11]
The sum of cubes of list is : 2555
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), constant extra space is required
Method #3 : Using math.pow() and sum() methods
Python3
test_list = [ 3 , 5 , 7 , 9 , 11 ]
print ( "The original list is : " + str (test_list))
x = []
for i in test_list:
import math
x.append(math. pow (i, 3 ))
res = int ( sum (x))
print ( "The sum of cubes of list is : " + str (res))
|
Output
The original list is : [3, 5, 7, 9, 11]
The sum of cubes of list is : 2555
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #4 : Using list comprehension:
Python3
test_list = [ 3 , 5 , 7 , 9 , 11 ]
print ( "The original list is :" , test_list)
res = sum ([num * * 3 for num in test_list])
print ( "The sum of cubes of list is :" , res)
|
Output
The original list is : [3, 5, 7, 9, 11]
The sum of cubes of list is : 2555
Time Complexity: O(N)
Auxiliary Space: O(1)
Method#5: Using for loop
Python3
def sum_of_cubes(lst):
res = 0
for num in lst:
res + = num * * 3
return res
test_list = [ 3 , 5 , 7 , 9 , 11 ]
print ( "The original list is:" , test_list)
print ( "The sum of cubes of list is:" , sum_of_cubes(test_list))
|
Output
The original list is: [3, 5, 7, 9, 11]
The sum of cubes of list is: 2555
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...