write a python program to print sum of 3 consecutive numbers in a range in a list. 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:-
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)
CodePudding user response:
This will give you the output you are looking for. It starts indexed at 1 instead of 0 and calls sum
on the lists you are creating in each iteration.
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)
CodePudding user response:
Using list comprehension - given a list and a length of interest lgt
:
l = list(range(1, 9))
lgt = 3
print([sum(l[i-lgt:i]) for i in range(lgt, len(l) 1)])
OUTPUT
[6, 9, 12, 15, 18, 21]
CodePudding user response:
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]
CodePudding user response:
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))
Output:
[6, 9, 12, 15, 18, 21]