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

คำนำหน้าอาร์เรย์ผลรวมในหลามโดยใช้ฟังก์ชันสะสม


รับอาร์เรย์และเราต้องทำอาร์เรย์ผลรวมนำหน้าโดยใช้ function.itertools.accumulate(iterable[, func]) โมดูลทำหน้าที่สร้างและส่งคืนตัววนซ้ำทั้งหมด ดังนั้นควรเข้าถึงได้โดยฟังก์ชันหรือลูปที่ตัดกระแสข้อมูลเท่านั้น สร้างตัววนซ้ำที่ส่งคืนผลรวมสะสม องค์ประกอบอาจเป็นประเภทที่เพิ่มได้ รวมถึงทศนิยมหรือเศษส่วน หากมีการระบุอาร์กิวเมนต์ของฟังก์ชันทางเลือก ก็ควรเป็นฟังก์ชันของสองอาร์กิวเมนต์และจะใช้แทนการบวก

ตัวอย่าง

Input:
Data = [1, 0, 2, 3, 5]
>>> list(accumulate(data))     # running summation
Output:
[1, 1, 3, 6, 11]

อัลกอริทึม

Step 1: Create list.
Step 2: Use list(accumulate( ))) function, its return running total. 
Step 3: Display total.

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

# Python program to print prefix
#sum array using accumulate function 
from itertools import accumulate 
  
def summation(A): 
   print ("The List after Summation ::>", list(accumulate(A))) 
  
# Driver program 
if __name__ == "__main__": 
   A=list()
n=int(input("Enter the size of the First List ::"))
print("Enter the Element of First  List ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)
summation(A) 

ผลลัพธ์

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