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

Prefix Sum Array ใน Python ด้วย accumulate (เวอร์ชัน 2)


บทความซ้ำกับ ID 1004106509 ใช้ itertools.accumulate คำนวณ prefix sum

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

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 First List: "))
    print("Enter the Elements:")
    for _ in range(n):
        A.append(int(input()))
    summation(A)

ผลลัพธ์

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