EPIJudge
EPIJudge copied to clipboard
CH17 Invariants has_two_sum.py wrong solution/test? Specific problem **buggy test**
Hello
I am moving through the book and encountered what I believe is an oversight.
Buggy test
The task: given a list of numbers A
, find if two numbers exist in the list that add up to a value t
.
The book implementation:
def has_two_sum(A: List[int], t: int) -> bool:
i, j = 0, len(A) - 1
while i <= j:
if A[i] + A[j] == t:
return True
elif A[i] + A[j] < t:
i += 1
else: # A[i] + A[j] > t.
j -= 1
return False
My implementation:
def has_two_sum(A: List[int], t: int) -> bool:
seen = dict()
for index, value in enumerate(A):
complement = t - value
if complement in seen:
return True
else:
seen[value] = index
return False
The test case I am having trouble with:
Test FAILED ( 53/1005) [ 28 us]
Arguments
A: [-2, -1, 1, 4]
t: 8
Failure info
expected: True
result: False
What happens with the book solution is that 4
is checked twice as A[i]
and A[j]
are checked for i = j = index = 3
, giving a total of 8 and a True
result. However if we go by what the task is asking this should not be the case: we can easily see that in the given array not two numbers sum up to 8.
I found that by changing the while clause to i < j
this is corrected.
Not sure this is a mistake in the solution or I have not correctly understood what is asked?