Python multiple solutions: Tracking sign, lazy evaluation, branchless, and one-liners
Using a loop, terminate early if a zero is encountered. Otherwise, invert the sign each time a negative value is encountered. This is the optimal solution in te
Using a loop, terminate early if a zero is encountered. Otherwise, invert the sign each time a negative value is encountered. This is the optimal solution in terms of complexity with O(N) ***in the worst case***.\n```\n    def arraySign(self, nums: List[int]) -> int:\n        sign = 1\n        for num in nums:\n            if num == 0:\n\t\t\t\treturn  0\n            elif num < 0:\n\t\t\t\tsign *= -1\n        return sign\n```\nHowever, since we are using python, it is sometimes just as fast or faster to compute a list product if done correctly, even though computing the list product has complexity O(N) even if `nums` contains zeros. The best way to do this is to trade lazy evaluation in pure python for the blazing speed of functions pre-compiled in `Standard C`.\n\nWe can use `math.prod` to do this\n```\n    def arraySign(self, nums: List[int]) -> int:\n\t\tproduct = prod(nums)\n        return 1 if product > 0 else -1 if product < 0 else 0\n```\n\nThe walrus assignment operator (`:=`) in `Python 3.8+` allows us to do this in one-line\n```\n    def arraySign(self, nums: List[int]) -> int:\n        return 1 if (product := prod(nums)) > 0 else -1 if product < 0 else 0\n```\n\nAnother built-in way to compute list products is to use `functools.reduce` with the `mul` operator\n```\n    def arraySign(self, nums: List[int]) -> int:\n        return 1 if (product := reduce(mul, nums)) > 0 else -1 if product < 0 else 0\n```\n\nUse can also define your own multiplication operator to use with `reduce` using lambdas\n```\n    def arraySign(self, nums: List[int]) -> int:\n        return 1 if (product := reduce(lambda x, y: x * y, nums)) > 0 else -1 if product < 0 else 0\n```\n\nAnd finally, we can use a `generator comprehension` inside whichever list product method you like.\n```\n    def arraySign(self, nums: List[int]) -> int:\n        return prod(1 if num > 0 else -1 if num < 0 else 0 for num in nums)\n```
['Python', 'Python3']