I have a prime_factorize function that returns a dictionary mapping from prime divisors to their powers. E.g., 50 = 2^1 * 5^2, so prime_factorize(50) returns {2 : 1, 5 : 2}.
Assuming this is the documented behavior, what would be the least surprising way to signal an error if called 0, 1, or a negative number? Throw ValueError? Return something that looks like correct output (e.g., prime_factorize(-5) -> {-1: 1, 5: 1})? return an empty dict?
And if you have a better format for returning a prime factorization, I’d love to hear that too.
In
prime_factorize(n):That way users a.) get meaningful info about what went wrong and b.) can handle the exception in a
try...exceptblock.I definitely wouldn’t turn incorrect data or an empty dict, because that will lead to some tricky debugging the first time someone passes an improper value. Raise exceptions, that’s what they’re there for!