面试中一行Python代码实现累加和的高效方案咨询
Great question! Your initial approach gets the job done, but as you pointed out, recalculating the sum from scratch for every element leads to redundant work—its time complexity is actually O(n²), which can slow things down significantly with large lists. Let's walk through a couple of better alternatives that are both elegant and efficient:
1. Use itertools.accumulate (Most Recommended)
Python's standard library has a built-in tool specifically for this kind of iterative accumulation. It reuses previous results, so it runs in O(n) time with no redundant calculations. Here's how to write it in a clean, readable way:
from itertools import accumulate def cum_sum(nums): return list(accumulate(nums))
If you want to cram it into a single line function definition (though splitting for readability is usually preferable), you can do:
from itertools import accumulate; cum_sum = lambda nums: list(accumulate(nums))
This leverages Python's optimized standard library code, making it both concise and performant.
2. Manual Accumulation with the Walrus Operator (No Imports)
If you can't or don't want to rely on external libraries, the walrus operator (:=) introduced in Python 3.8 lets you track the running total directly in a list comprehension. This also runs in O(n) time:
def cum_sum(nums): total = 0 return [total := total + num for num in nums]
Or as a single line function:
def cum_sum(nums): total=0; return [total := total + num for num in nums]
This keeps everything self-contained while avoiding the redundant sum calculations of your original solution.
Quick Note on Your Original Approach
To clarify why your initial code isn't ideal: return [sum(nums[0:i+1]) for i in range(len(nums))] works, but for each element at index i, it has to sum all elements from the start up to i. For a list of size n, that adds up to 1 + 2 + ... + n = n(n+1)/2 operations—hence the O(n²) time complexity. The alternatives above fix this by carrying over the total from one step to the next.
内容的提问来源于stack exchange,提问作者yangcs11

