Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาผลรวมสะสม (Cumulative Sum) ของลิสต์ใน Python

โจทย์: กำหนดลิสต์ สร้างลิสต์ใหม่ที่แต่ละตำแหน่งเป็นผลรวมสะสมจากต้นมาจนถึงตำแหน่งนั้น

ตัวอย่าง

Input: [10, 20, 30, 40, 50]
Output: [10, 30, 60, 100, 150]

ตัวอย่างโค้ด Python

def cumulative_sum(lst):
    result = []
    cumsum = 0
    for element in lst:
        cumsum += element
        result.append(cumsum)
    return result

# ทดสอบ
lists = [10, 20, 30, 40, 50]
print("New list:", cumulative_sum(lists))
# Output: [10, 30, 60, 100, 150]

วิธี Alternative: itertools.accumulate

from itertools import accumulate

lists = [10, 20, 30, 40, 50]
print(list(accumulate(lists)))  # [10, 30, 60, 100, 150]

วิธี Alternative: NumPy

import numpy as np

lists = [10, 20, 30, 40, 50]
print(np.cumsum(lists))  # [10 30 60 100 150]

ประยุกต์ใช้

  • Financial: Running balance
  • Statistics: CDF, Percentiles
  • Signal Processing: Integration

ความซับซ้อน: Time O(n), Space O(n)