首页 > 编程知识 正文

Python 中的累积和程序

时间:2023-11-25 15:30:10 阅读:309188 作者:MSWZ

累计总和是多少?

累计的总和意味着“到目前为止有多少”。累积和的定义是给定序列的和,该序列随着更多的加法而增加或变大。累积总和的真实例子是秋千池里不断增加的水量。

示例:


Input: 10, 15, 20, 25, 30
Output: 10, 25, 45, 70, 100

Input: 1, 2, 3, 4, 5 6, 7 ,8, 9, 10
Output: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55

程序:1


# Cumulative sum
def Cumulative_sum(lists): 
    cum_list = [] 
    length = len(lists) 
    cum_list = [sum(lists[0:x:1]) for x in range(0, length+1)] 
    return cum_list[1:]

lists = [10, 15, 20, 25, 30] 
print (Cumulative_sum(lists))

输出:

10, 25, 45, 70, 100

程序:2


list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
cum_list=[] 
y = 0
for x in range(0,len(list)):
    y+=list[x]
    cum_list.append(y) 

print(cum_list) 

输出:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55

程序 3:用户定义程序


i = []
n = int(input("enter the no of elements in list:"))
for x in range(0,n):
    element=int(input("enter the element" + str(x+1) + ":"))
    i.append(element)
j=[sum(i[0:x+1]) for x in range(0,len(i))]
print("Original list is: ",i)
print("Cumulative sum list is: ",j)

输出:

enter the no of elements in list: 10
enter the element1: 2
enter the element2: 3
enter the element3: 8
enter the element4: 6
enter the element5: 45
enter the element6: 32
enter the element7: 56
enter the element8: 32
enter the element9: 14
enter the element10: 25
Original list is: [2, 3, 8, 6, 45, 32, 56, 32, 14, 25]
Cumulative sum list is: [2, 5, 13, 19, 64, 96, 152, 184, 198, 223]

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。