from sys import stdin, stdout
t=int(stdin.readline())
while t:
t-=1
arr=[]
n,q=map(int, stdin.readline().split())
for i in range(q):
x=list(map(int, stdin.readline().split()))
arr.append(x)
s=0
for i in range(len(arr)):
if i==0:
s+=abs(arr[0][1])
else:
s+=abs(arr[i][1]-arr[i][0])
s+=abs(arr[i-1][1]-arr[i][0])
print(arr)
stdout.write(str(s))
Could you please explain your approach also So that the one who dont know python can figure out?
Hi @sagar7742. Here is the modified version of your code.
# cook your dish here
from sys import stdin, stdout
t=int(stdin.readline())
while t:
t-=1
arr=[]
n,q=map(int, stdin.readline().split())
for i in range(q):
x=list(map(int, stdin.readline().split()))
arr.append(x)
s=0
for i in range(len(arr)):
if i==0:
s+=(arr[0][0])+abs(arr[0][1]-arr[0][0])
else:
s+=abs(arr[i][1]-arr[i][0])
s+=abs(arr[i-1][1]-arr[i][0])
#print(arr)
stdout.write(str(s)+"\n")
The following were the corrections I made in the code:
- Indented the code after while loop (Don’t know if it is copy-paste error)
- Commented the
print(arr)
line from second to last. You don’t want to be prinitng the whole array in the output. - For the first request, we need to add the source floor’s distance from ground floor i.e. add
arr[0][0]
tos
as well as the abosulte difference between the destination and source of the first request i.e.abs(arr[0][1]-arr[0][0])
. - Added a
"\n"
tostdout.write
since it does not create a newline automatically after every operation.
Cheers