Skip to content

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:

Input
a=10, b=20
Output
True
Input
a=-5, b=-15
Output
True
Input
a=0, b=0
Output
True
Input
a=0, b=10
Output
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):
    sign = lambda x: 0 if x == 0 else (1 if x > 0 else -1)
    return sign(a) == sign(b)
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.

import math

def same_sign(a, b):
    if a == 0 and b == 0:
        return True
    if a == 0 or b == 0:
        return False
    return math.copysign(1, a) == math.copysign(1, b)

math.copysign(1, x) returns 1.0 if x > 0 and -1.0 if x < 0. Handle zero explicitly first since copysign treats 0 as positive.

same_sign = lambda a, b: (
    (a > 0 and b > 0) or (a < 0 and b < 0) or (a == 0 and b == 0)
)

Key takeaways

01

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.

02

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.

03

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.