-3

my code

for i in range(3):
    A=(list(map(int, input().split())))
    for i in range(1,len(A)):
        stk=(A[i]-(A[i-1]+1))
        print(stk)

result input (1 3 4) (1 3 5) (1 2 3 4 5)

1 3 4
1
0
1 3 5
1
1
1 2 3 4 5
0
0
0
0

I want to add stk each(eg. 1/2/0) please tell me how to add stk

김도영
  • 17
  • 4

1 Answers1

1

Use the sum function to sum an iterable (you can easily convert your for loop into a simple generator that produces all the values of stk):

A = [int(i) for i in input().split()]
print(sum(
    A[i]-(A[i-1]+1)
    for i in range(1,len(A))
))

This is equivalent to doing:

A = [int(i) for i in input().split()]
total = 0
for i in range(1, len(A)):
    total += (A[i] - (A[i-1] + 1))
print(total)

(Note that when you compute a sum by storing it in a variable, you should not give it the name sum, because that will shadow the name of the very useful sum function!)

You can also do this kind of pairwise iteration with zip:

print(sum(
    b - a - 1 
    for a, b in zip(A, A[1:])
))
Samwise
  • 68,105
  • 3
  • 30
  • 44