S1Q3 · Check If Both Numbers Have the Same Sign¶
⚡ Quick Reference
Function: same_sign(a, b) -> bool
Core idea: extract the sign of each number as -1, 0, or 1 using a helper, then compare.
def same_sign(a, b):
sign = lambda x: 0 if x == 0 else (1 if x > 0 else -1)
return sign(a) == sign(b)
Key rules:
- Three sign categories: positive (> 0), negative (< 0), zero (== 0)
- same_sign(0, 10) → False - zero is its own category, not positive or negative
- Both must be in the same category
Problem Statement¶
Problem
Write a function same_sign(a, b) that returns True if both numbers are strictly positive, both strictly negative, or both zero.
Examples:
a=10, b=20
True
a=-5, b=-15
True
a=0, b=0
True
a=0, b=10
False
Tracing all examples¶
a |
b |
sign(a) |
sign(b) |
Same? | Result |
|---|---|---|---|---|---|
| 10 | 20 | +1 | +1 | ✅ | True |
| -5 | -15 | -1 | -1 | ✅ | True |
| 0 | 0 | 0 | 0 | ✅ | True |
| 10 | -20 | +1 | -1 | ❌ | False |
| 0 | 10 | 0 | +1 | ❌ | False |
Solution approaches¶
def same_sign(a, b):
both_positive = a > 0 and b > 0
both_negative = a < 0 and b < 0
both_zero = a == 0 and b == 0
return both_positive or both_negative or both_zero
Most readable - directly states each of the three valid cases. No helper function needed.
Key takeaways¶
Zero is its own sign category
The problem treats zero separately from positive and negative. same_sign(0, 10) is False even though both might appear "non-negative". Always handle zero as a distinct third case.
Three explicit cases - most readable
both_positive or both_negative or both_zero directly maps to the problem statement. Each condition is self-explanatory - no mental decoding of sign tricks needed.
sign(a) == sign(b) - compact and extensible
Mapping each number to its sign value (-1, 0, 1) and comparing is compact. Works for any number of arguments if extended to len(set(map(sign, nums))) == 1.