Just comparing sums...
def findErrorNums(self, nums):
return [sum(nums) - sum(set(nums)), sum(range(1, len(nums)+1)) - sum(set(nums))]
Hi @StefanPochmann -- I think @4acreg is mentioning that instead of calculating the sum of the series by invoking sum() over the range [1:n], you can instead use the formula n(n+1)/2. BTW - you are an amazingly smart and talented person to watch here. I have learned a lot from your Python solutions. Thanks so much! -Clayton
def findErrorNums2(self, nums):
return [sum(nums) - sum(set(nums)), len(nums)*(len(nums)+1)//2 - sum(set(nums))]
Looks like this does improve execution time very slightly... Is this a legit test though? I'm not sure how to measure Python performance accurately.
def findErrorNums(self, nums):
return [sum(nums) - sum(set(nums)), sum(range(1,len(nums)+1)) - sum(set(nums))]
def findErrorNums2(self, nums):
return [sum(nums) - sum(set(nums)), len(nums)*(len(nums)+1)//2 - sum(set(nums))]
if __name__ == '__main__':
solution = Solution()
#
# create test data
#
nums = []
n = 10000
for i in range(1,n+1):
nums.append(i)
nums[1] = 3 # change 2 to 3 ( 3 is a duplicate and 2 is missing )
#
# time execution
#
from timeit import default_timer as timer
start = timer()
print(solution.findErrorNums(nums))
end = timer()
print(end - start)
start = timer()
print(solution.findErrorNums2(nums))
end = timer()
print(end - start)
Output:
[3, 2]
0.0030322519596666098
[3, 2]
0.0018974849954247475
@claytonjwong Yeah I've known n(n+1)/2 for about 30 years and used it many times. Here I chose not to. Five of my twelve solutions that I have in the editor actually use it, but I like the above solution best.
Your test is indeed bad. Times this small aren't trustworthy. Especially since you're even printing during the timing. Printing is slow. You might effectively measure the printing instead of the calculation. Better make it take at least one second or so, by using a larger list or repeating the calculation often enough. And do just calculation, no printing (during the timing).
Btw, you can simply do nums = list(range(1, n+1))
instead of that loop.
Or if you want to confuse/educate people a bit, do nums, nums[1] = list(range(1, n+1)), 3
:-)