Return true if every number in the slice is even, and false otherwise.
An empty slice counts as all even (there's no odd number in it).
allEven(nums)
allEven([]int{2, 4, 6, 8}) // → true
allEven([]int{2, 4, 5, 8}) // → false
allEven([]int{}) // → true
The question is really: "is there a single counterexample anywhere in this list?" Flip it around — every element is even exactly when no element is odd. So you're hunting for the first odd number, and if you never find one, the answer is yes.
A number is even if dividing it by two leaves no remainder: n % 2 === 0. That works the same way for negative numbers too — you're just checking each number on its own, no need to look at the rest of the list.
The moment you find one odd number, you're done — the answer is false, no matter what else is in the list. Return immediately instead of finishing the scan. In the common case where the answer is "no," you might catch that on the very first element. Only when the answer really is "yes" do you end up checking everything — and that's unavoidable, since you can't be sure there's no odd number until you've looked everywhere.
What if the list is empty? "Every element is even" is trivially true when there are no elements to break the rule — there's nothing to disprove it. If your loop just does nothing on an empty list and you return true by default afterward, this falls out naturally, no special case needed.
You could collect every remainder first, or count the odd numbers and check if that count is zero. Both work, but both force you to look at every element even when an early one already settles the answer, and both use memory you don't need. A single early-exit scan is simplest, fastest in the common case, and never does more work than necessary.
def all_even(nums):
for n in nums:
if n % 2 != 0:
return False
return True
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.