算法(Python程序查找列表的累积和)

本文概述

  • Python3
  • Python3
问题陈述要求产生一个新列表, 该列表的i ^ {th}元素等于(i +1)元素的总和。
例子 :
Input : list = [10, 20, 30, 40, 50] Output : [10, 30, 60, 100, 150]Input : list = [4, 10, 15, 18, 20] Output : [4, 14, 29, 47, 67]

推荐:请尝试以下方法
{IDE}
首先, 在继续解决方案之前。
方法1:
我们将使用列表理解和列表切片的概念来获取列表的累积总和。列表理解已用于访问列表中的每个元素, 并且切片已完成从头到i + 1元素的访问。我们使用sum()方法总结了列表中从开始到i + 1的元素。
下面是上述方法的实现:
Python3
# Python code to get the Cumulative sum of a list def Cumulative(lists): cu_list = [] length = len (lists) cu_list = [ sum (lists[ 0 :x: 1 ]) for x in range ( 0 , length + 1 )] return cu_list[ 1 :] # Driver Code lists = [ 10 , 20 , 30 , 40 , 50 ] print (Cumulative(lists))

【算法(Python程序查找列表的累积和)】输出:
[10, 30, 60, 100, 150]

方法二:
Python3
list = [ 10 , 20 , 30 , 40 , 50 ] new_list = [] j = 0 for i in range ( 0 , len ( list )): j + = list [i] new_list.append(j)print (new_list) #code given by Divyanshu singh

输出:
[10, 30, 60, 100, 150]

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

    推荐阅读