Problem overview
The method positiveSquares gets a list nums of integers and returns a new list with the square of every number above 0, in the original order. Zero and negative numbers are left out. If no number is above 0, or the list is empty, the answer is the empty list.
For [3, -1, 0, 4] the answer is [9, 16]. Only 3 and 4 are above 0, and their squares are 9 and 16.
Approach
Two things happen to the numbers: some are dropped (a filter), and the rest are changed (a map). A list comprehension holds both in one line. The if at the end decides which numbers get in, and the front part says what each accepted number becomes.
The order of work matters. The if runs first, on the original number, so negative numbers never get squared. This is important because a square is never negative: if you squared everything first, -1 would become 1 and could not be told apart from a real 1.
Step by step
- Build
squareswith one comprehension:num * numfor eachnuminnums, withif num > 0at the end. - Return
squares.
The solution in Python
class Solution:
def positiveSquares(self, nums: List[int]) -> List[int]:
squares = [num * num for num in nums if num > 0]
return squares
The condition is num > 0, strict, so 0 is left out as the statement asks. When nothing passes, the comprehension builds an empty list, and that is the right answer, so no special case is needed. The same holds for an empty input list.
Testing
[3, -1, 0, 4] -> [9, 16]
[-5, -2, 0] -> []
[1, 2, 3] -> [1, 4, 9]
[] -> []
Without the if, the first list would give [9, 1, 0, 16]: every number squared, including the ones that should be left out.
Why a comprehension fits
The same result needs four lines with a loop: make an empty list, loop over nums, test num > 0, append num * num. The loop is a fine answer too. The comprehension is worth learning because "keep some, change them" is such a common job, and reading it as "squares of the numbers above 0" is close to how you would say it aloud. The numbers are between -1000 and 1000, so the squares are at most a million, which Python holds without any overflow concern.
Squaring with another operator
You could also write num ** 2 for the square; num * num and num ** 2 give the same integer. The lesson writes num * num, the statement's own definition of a square: "the number times itself". Whichever you choose, keep it inside the front part of the comprehension and leave the condition alone.
Common mistakes
- Using
num >= 0, which keeps 0 and adds a 0 to the result. - Putting the
ifin front of thefor. A comprehension with a filter has the form[value for item in items if condition];ifat the front needs anelseand does something else. - Returning
Noneor printing when nothing passes. The answer is an empty list. - Changing
numsin place. The method returns a new list.
