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

Prefix Sum Array ใน Python ด้วย accumulate


สร้าง prefix sum array (running summation) โดยใช้ itertools.accumulate() ซึ่งคืน iterator ที่สะสมผลรวม

ตัวอย่าง

Input: [1, 0, 2, 3, 5]
Output: [1, 1, 3, 6, 11]

อัลกอริทึม

  1. สร้าง list
  2. ใช้ list(accumulate(list)) ได้ running total
  3. แสดงผล

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

from itertools import accumulate

def summation(A):
    print("The List after Summation:", list(accumulate(A)))

if __name__ == "__main__":
    A = []
    n = int(input("Enter the size of the List: "))
    print("Enter the Elements:")
    for _ in range(n):
        k = int(input())
        A.append(k)
    summation(A)

ผลลัพธ์

Enter the size of the List: 5
Enter the Elements:
1
2
3
4
5
The List after Summation: [1, 3, 6, 10, 15]