Skip to content

Instantly share code, notes, and snippets.

@clamytoe
Created October 11, 2018 13:26
Show Gist options
  • Save clamytoe/b43c435f2a39e58537e273c1528bee9b to your computer and use it in GitHub Desktop.
Save clamytoe/b43c435f2a39e58537e273c1528bee9b to your computer and use it in GitHub Desktop.
xor.py
""" xor.py
My attempt to complete the challenge at:
https://www.geeksforgeeks.org/calculate-xor-1-n/
"""
import timeit
from functools import reduce
def mod(n):
"""use the modulos to speed up the calculation"""
remainder = n % 4
if remainder == 0:
return n
elif remainder == 1:
return 1
elif remainder == 2:
return n + 1
elif remainder == 3:
return 0
else:
return normal(n)
def normal(n):
"""normal brute force attempt"""
nums = range(1, n+1)
return reduce(xor, nums)
def xor(a, b):
"""calculates the xor of two numbers"""
return a ^ b
def normal_times(n):
setup_code = """
from __main__ import normal, xor
"""
test_code = """
n = {}
x = normal(n)
""".format(n)
ntimes = timeit.repeat(
setup = setup_code,
stmt = test_code,
repeat = 3,
number = 10000
)
print(f' normal: {min(ntimes)}')
def mod_times(n):
setup_code = """
from __main__ import mod, normal, xor
"""
test_code = """
n = {}
x = mod(n)
""".format(n)
ntimes = timeit.repeat(
setup = setup_code,
stmt = test_code,
repeat = 3,
number = 10000
)
print(f'modulos: {min(ntimes)}')
if __name__ == '__main__':
n = 6
normal_times(n)
mod_times(n)
n_xor = normal(n)
m_xor = mod(n)
print(f'normal({n}) => {n_xor}')
print(f' mod({n}) => {m_xor}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment