Instagram
youtube
Facebook
Twitter

Python Array Index program Codechef solution

Python Array Index programme Codechef solution

Problem

Given an array A of size N and an integer K, check if there exists any pair of index i,j such that Ai+Aj=K and i=j.

Input

  • The first line of the input contains a single integer, T, denoting the number of test cases.
  • The first line of each test case contains two space-separated integers, N and K, respectively.
  • The second line of each test case contains N space-separated integers Ai.

Output

For each test case, print a single line containing the answer "Yes" or "No" (without quotes).

Constraints

  • 1≤T≤100
  • 2<=N<=10^4
  • 1<=K<=10^9
  • 1<Ai<=10^9

Example Input

3

4 3

1 2 1 3

4 6

1 2 1 3

5 1

5 4 1 2 3

Example Output

Yes

No

No

Explanation:

Example case 1: A1 + A2 = 3.

Example case 2: A pair having Ai + Aj = 6 doesn’t exist.

Example case 2: A pair having Ai + Aj = 1 doesn’t exist.

Solution:

try:

    t=int(input(“Enter the number of terms: “))

    while(t):

        n,k=map(int, input(“Enter an array size and a number: “).split())

        a=[int(x) for x in input(“Enter numbers separated by space: “).split()]

        c=0

        for i in range(n-1):

            for j in range(i+1, n):

                if(a[i]+a[j]==k):

                    c=1

                    break

            if c==1:

                break

        if c==1:

            print("Yes")

        else:

            print("No")

        t-=1

except:

    pass

         Steps to solve this problem:

  1. In the try block, ask the user to enter a number of terms.
  2. In the while loop, ask the user to enter the size of an array and a number, and using the map() function, get iterator objects and store them in variables n and k.
  3. Using list comprehension, make a list of elements taken by the user.
  4. Initialise the variable c with 0.
  5. In a nested loop, if a[i] + a[j] is equal to k, then re-assign the value of c to 1 and break the statement.
  6. Check if c is equal to 1, then break from the outer loop.
  7. Again, Check if c is equal to 1, then print "yes," otherwise print "no."
  8. In the except block, use the pass statement to keep it empty.