Arithmetic Sequence @ Dcoder

in #programminglast year

Problem: In mathematics, an arithmetic progression (AP) or arithmetic sequence is a sequence of numbers such that the difference between the consecutive terms is constant. John was writing an Arithmetic sequence with N terms, but while writing he mistakenly made one wrong entry and he is sure that first term is right. Help him to find the wrong term entered by him.
Input: The first line of input contains a single line T, which represents the number of testcases.
Then first line of each test case contains an integer N :Total number of terms.
Then N space separated integers denoting the sequence.
Output: For each test case.
Print the wrongly entered term.
Constraints: 1<=T<=100.
4<=N<=1000.
1<=Terms<=1000.
Sample Input: 2
5
1 3 5 6 9
4
1 2 3 5
Sample Output:
6
5

for t in range(int(input())):
  n = int(input())
  ap = tuple(map(int, input().split()))
  d = (ap[-1] - ap[0]) // (n - 1)
  if ap[1] - ap[0] != d:
    if ap[2] - ap[1] == ap[1] - ap[0]:
      print(ap[-1])
    elif ap[2] - ap[1] == d:
      print(ap[0])
    else:
      print(ap[1])
  else:
    for i in range(2, n):
      if ap[i] - ap[i-1] != d:
        print(ap[i])
        break