Python 中使用 accumulate 函式建立字首和陣列


給定一個數組,我們必須使用 accumulate 函式製作字首和陣列。itertools.accumulate(iterable[, func]) 模組函式全部構造並返回迭代器。因此,它們僅應該透過截斷流的函式或迴圈訪問。生成返回累加總和的迭代器。元素可以是任何可加型別,包括 Decimal 或 Fraction。如果提供了可選函式引數,它應該是兩個引數的函式,它將被用作加法運算。

示例

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]

更新於: 2020-06-25

414 次瀏覽

開啟您的 職業生涯

完成課程取得認證

開始學習
廣告
© . All rights reserved.