Ask coding questions

← Back to all posts
How to write function that returns True if any pair of numbers in a list sum to zero.
BhaiBhai

How to write a function that takes in a list of integers (positive or negative) and returns True if any pair of the numbers in the list sum to 0, Otherwise, return False

Voters
BhaiBhai
Comments
hotnewtop
SixBeeps

You're sooo close to being correct. The only issue here is that the function escapes way too early, and it only ends up doing one comparison total instead of a comparison for every pair in the list.

The first two lines here are perfect: it will return True if the current pair adds up to zero. The second two lines, however, will stop the function if it doesn't add up to zero before it can even check the other pairs. Instead, what you should do is to return False only when both loops are completely finished looking through the list. In other words, remove those two lines and slap a return False at the end of SumZero().

Another issue here is that your function checks list elements with themselves. By that, I mean if your list looks like [2, 1, 8, 3], it will check 2+2, 1+1, 8+8, and 3+3. That doesn't sound like an issue until you have a 0 in the list, where 0+0=0. Since an element twice doesn't technically count as a pair, you should avoid doing that. Try fixing that yourself, but if you need help, I'd be willing to show you how that's done.

BhaiBhai

You said "Instead, what you should do is to return False only when both loops are completely finished looking through the list."

I just don't know how to make sure the loops completely finish. This happens to me a lot of times, and I just don't know how.

SixBeeps

@BhaiBhai Any code you put after the loops in the same scope with only run once they have finished. In your case, as I said, just return False at the end of your function.

BhaiBhai
BhaiBhai

Your responsesare really detailed and easy to understand

SixBeeps

@BhaiBhai You definitely fixed the looping logic, but there's still one issue with the double-checking bug.

Take this array:

As we saw, the program shouldn't consider element 3 twice. Your code checks for this and correctly excludes it, but it also excludes elements 3 and 5, which is a valid pair.

Sorry if this explanation doesn't make much sense, it's hard to explain what you need without just giving you the code.