Python XOR and Arrays | Competitive Coding Questions

Python Competitive Coding Questions | XOR and Arrays: This practice is based on XOR and Arrays in Python programming language. Submitted by Prerana Jain, on April 22, 2020

Question

John loves XOR. John's friends always ask him doubts related to XOR and he helps them to solve problems but he is busy because of his exams and asks you to help his friends. One of his friends wants your help with the following problem. Given an array of N numbers and a number K. The task is to insert the number in the given array such that the bitwise XOR of all the elements in the new array equals the give input K.

Input

The first line of input contains an integer T denoting the numbers of test cases.

The first line of each test case consists of 2 integers denoting N and K. The second line of each test case consists of N-space integers denoting the array.

1
5  10
1  2  3  4  5

Output

For each test case print the number by inserting which the XOR of all the elements in the array becomes equal to K.

Explanation:
1^2^3^4^5^11 = 10

Output:
11

Constraints

1 <= T <100
1<N, K = 100
1 <= array elements <= 10^3

To solve this question, we are using Python3.

Bitwise XOR Operation

In python, bitwise operators are used to perform the bitwise operation on integers. Firstly the integers are converted into binary digit and then bit by bit operation is performed and the result is returned in the decimal format.

XOR operation table,

OperationResult
0^00
0^11
1^00
1^10

Python Code

# Input test case (T)
print("Input test case: ")
t = int(input())

while(t>0):
  t=t-1

  # Input value of m and k 
  print("Input value of m and k: ") 
  m,k=list(map(int,input().split()))

  # Input array elements
  print("Input array elements: ")
  arr=list(map(int,input().split()))

  # Store first value
  res=arr[0]
  for i in range(1,m):
    # Perform the bitwise XOR operation 
    # on elements in array
    res=res^arr[i]

  # print the result
  print("Result is: ")
  print(k^res)

Output

Input test case: 
1
Input value of m and k: 
5 10
Input array elements: 
1 2 3 4 5
Result is: 
11

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.