Prime_factorize (1) ->? (Pythonic Error Alarm)

I have a function prime_factorizethat returns dictionary matching from simple dividers to its credentials. For example, 50 = 2 ^ 1 * 5 ^ 2, therefore prime_factorize(50)returns {2 : 1, 5 : 2}.

Assuming this is documented behavior, what would be the least surprising way to report an error if it is caused by 0, 1, or a negative number? Give up ValueError? Return what looks like the correct output (e.g. prime_factorize(-5) -> {-1: 1, 5: 1})? return empty dict?

And if you have a better format for returning simple factorization, I would also like to hear that.

+3
source share
4 answers

In prime_factorize(n):

if n < 2 or not isinstance(n, numbers.Integral):
    raise ValueError("Number to factor can't be less than 2")
else:
    # normal behavior

, a.) , , b.) try...except.

dict, , - . , !

+2

, . 2- ? I.e., prime_factor(50) return [(2,1), ((5,2)].

, , , , .

+1

, python; x < 2 .

0

The math functions in the standard library can be a good reference to the least surprising behavior. For example, check math.sqrt: it returns a ValueErrordomain error (here n <1) and TypeErrorwith an unexpected type (here, if you send a non-integer number). Therefore, I would write.

if is not isinstance(n, numbers.Integral):
    raise TypeError("an integer is required")
elif n < 1:
    raise ValueError("number to factor can't be less than 1")
...

And I agree with Piotr Findeisen, factoring 1 as an empty dictionary seems perfectly healthy.

0
source

Source: https://habr.com/ru/post/1780992/


All Articles