[英]python program to print sum of consecutive numbers in a range
write a python program to print sum of 3 consecutive numbers in a range in a list.编写一个 python 程序来打印列表中某个范围内的 3 个连续数字的总和。 for example we take input n = 8 so the program will print [1+2+3,2+3+4,3+4+5,4+5+6+,5+6+7,6+7+8] means the output should be =[6,9,12,15,18,21] i am new in programming, my code is:-
例如我们输入 n = 8 所以程序将打印 [1+2+3,2+3+4,3+4+5,4+5+6+,5+6+7,6+7+8 ]表示 output 应该是 =[6,9,12,15,18,21] 我是编程新手,我的代码是:-
arr=[]
N=int(input("enter the value of N"))
def lst(arr):
for i in range(N):
x=[i]+[i+1]+[i+2]
arr.append(x)
lst(arr)
print(arr)
This will give you the output you are looking for.这将为您提供您正在寻找的 output。 It starts indexed at 1 instead of 0 and calls
sum
on the lists you are creating in each iteration.它从 1 而不是 0 开始索引,并在每次迭代中创建的列表上调用
sum
。
Edit: as pointed out in the comments, creating these lists is unnecessary you can just do a sum.编辑:正如评论中所指出的,创建这些列表是不必要的,你可以做一个总和。
arr=[]
N=int(input("enter the value of N"))
def lst(arr):
for i in range(1, N - 1):
x = (i) + (i + 1) + (i + 2) # for ease of reading
arr.append(x)
lst(arr)
print(arr)
Using list comprehension - given a list and a length of interest lgt
:使用列表理解 - 给定一个列表和感兴趣的长度
lgt
:
l = list(range(1, 9))
lgt = 3
print([sum(l[i-lgt:i]) for i in range(lgt, len(l) + 1)])
OUTPUT OUTPUT
[6, 9, 12, 15, 18, 21]
Why can't you use list comprehension,为什么你不能使用列表理解,
In [1]: [(i+1) + (i+2) + (i+3) for i in range(7)]
Out[1]: [6, 9, 12, 15, 18, 21, 24]
You could try this improved version using the math insight: too:您也可以使用数学洞察力尝试这个改进的版本:
arr=[]
N = int(input("enter the value of N"))
def lst(arr):
for i in range(1, N - 1):
tot = (i + 1) * 3 # for ease of readings
arr.append(tot)
lst(arr)
print(arr)
# List Comp:
def lst_sum(N):
return [(i + 1) *3 for i in range(1, N-1)]
print(lst_sum(8))
[6, 9, 12, 15, 18, 21]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.