Quick Overview
sum(n**3 for n in range(x)) streams one value at a time, where the bracketed comprehension materialises every cube first. Same answer, O(1) memory against O(n).
Create a function sum_of_cubes(nums) that takes a list of numbers and returns the sum of its cubes (n^3).
Generator expressions paired with sum() enable performing mathematical transformations across datasets without allocating intermediate lists in memory.
Use Python's built-in sum() with a generator expression x**3:
def sum_of_cubes(nums):
return sum(x**3 for x in nums)
# Testing our function
print(sum_of_cubes([1, 5, 9])) # Output: 855 (1 + 125 + 729)
print(sum_of_cubes([3, 4, 5])) # Output: 216 (27 + 64 + 125)
print(sum_of_cubes([2])) # Output: 8
print(sum_of_cubes([])) # Output: 0
In Python, x**3 raises x to the power of 3 (do NOT use x ^ 3, as ^ is Python's bitwise XOR operator!).
x ^ 3 performs bitwise XOR logic, NOT exponentiation! Always use double asterisks x ** 3 or pow(x, 3) for powers in Python.Use ** for exponents and sum() for aggregations. Next, let's check for symmetrical numbers and palindromes!
A function with no return hands back None, so a forgotten one surfaces as a TypeError at the call site rather than at the line that actually caused it.
minutes * 60 returns an int when given an int, while / always produces a float regardless of the operands. Multiplication preserves the type; division does not.
base * height / 2 always yields a float in Python 3 because / never returns an int, even for whole numbers. // floors instead, which is almost never what an area wants.