cython ( , , , ):
Create a file singleNumber.pyxwith the following contents:
def singleNumber(list nums, int nn):
cdef int i, ii, np
cdef list prev = []
for i in xrange(nn):
np = len(prev)
for ii in xrange(np):
if nums[i] == prev[ii]:
nums[i] = - prev[ii]
else:
prev.append(nums[i])
return sum(nums)
Create a file setup.pywith the following contents:
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize('singleNumber.pyx'),
)
Compile it: python setup.py build_ext --inplace
import singleNumber as sn
arr = [i + 1 for i in range(1000)]
%timeit sn.singleNumber(arr,len(arr))
Result: 100000 loops, best of 3: 15.4 µs per loop
Using the function XORgives me:10000 loops, best of 3: 82.1 µs per loop
EDIT:
I get different results if I use solutions XORcompared to the original function!
from operator import xor
def singleNumber_xor(nums):
return reduce(xor, nums)
arr = [i + 1 for i in range(10000)]
singleNumber_xor(arr)
Gives me: 10000
Original function:
def singleNumber_orig(nums):
prev = set([])
for i,j in enumerate(nums):
if j in prev:
nums[i] = -j
else:
prev.add(j)
return sum(nums)
singleNumber_orig(arr)
Gives me: 50005000
source
share