Compute binary XOR of all integers in a range, mod 2 here I am taking 3 inputs. 1st input will take test cases and the other two input will take starting and ending range. the program is running fine as expected but the limit of this question for compilation is 1 sec, and my code is taking 5.01 sec.

How can I make it more efficient so that I can submit the code?


  The challenge was to take number of test cases.
  
  Each test cases show take 2 input (starting and ending range) Eg: 1  4
  (i.e 1,2,3,4)
  
  Do the bitwise XOR operation for all of them (i.e  1^2^3^4) 
  
  Which when
  you perform will be equal to 4
  
  Now just check if it is even or odd and print the same.


Here's my code:

from sys import stdin, stdout
t = stdin.readline()
for i in range(int(t)):
    p = 0
    a, b = map(int,stdin.readline().split())
    for x in range(a,b+1):
        p ^= int(x)
    if p % 2 == 0:
        stdout.write(str("Even\n"))
    else:
        stdout.write(str("Odd\n"))


compiling in python 3.6

INPUT:
    4 
    1 4
    2 6
    3 3
    2 3

OUTPUT:
    Even
    Even
    Odd
    Odd


Working perfectly with no issue in code.
Welcome to CR, nice challenge

A few comments about the code


Many unnecessary conversion

Python is a duck typed language, if it talks like a duck, walks like a duck... it must be a duck!

This means that


p ^= int(x)



Here x is already an int, same goes for the str conversion later
Use _ variable names for variable you don't use


  for i in range(int(t)):


Replace the i with _
You could return directly


if p % 2 == 0:
    return "Even"
else:
    return "Odd"



Instead, you could do which uses a ternary operator

return "Even" if p % 2 == 0 else "Odd"

As for the speedup

I've used this SO link to inspire me, which does a way better job of explaining this then I could ever do

In short there is a trick to get the XOR'd product of a certain range

Using the method from the link, I get a massive speedup,

For these timings: range(1, 1000)

Bitmagic:  0.023904799999999997
OP: 2.2717274



Code

# https://stackoverflow.com/questions/10670379/find-xor-of-all-numbers-in-a-given-range
def bit_magic(bound):
    magic = [bound, 1, bound + 1, 0]
    return magic[bound % 4]

def bitwise_check(lower_bound, upper_bound):
    p = bit_magic(upper_bound) ^ bit_magic(lower_bound - 1)
    return "Odd" if p &amp; 1 else "Even"

def main():
    n = int(input("Number of testcases: "))
    for _ in range(n):
        lower_bound, upper_bound = map(int, input().split())
        print(bitwise_check(lower_bound, upper_bound))

if __name__ == '__main__':
    main()