Why doesn't Python have a sign function?

前端 未结 12 702
旧巷少年郎
旧巷少年郎 2020-12-02 04:54

I can\'t understand why Python doesn\'t have a sign function. It has an abs builtin (which I consider sign\'s sister), but no si

12条回答
  •  眼角桃花
    2020-12-02 05:06

    Since cmp has been removed, you can get the same functionality with

    def cmp(a, b):
        return (a > b) - (a < b)
    
    def sign(a):
        return (a > 0) - (a < 0)
    

    It works for float, int and even Fraction. In the case of float, notice sign(float("nan")) is zero.

    Python doesn't require that comparisons return a boolean, and so coercing the comparisons to bool() protects against allowable, but uncommon implementation:

    def sign(a):
        return bool(a > 0) - bool(a < 0)
    

提交回复
热议问题