-
-
Notifications
You must be signed in to change notification settings - Fork 45.6k
/
signum.py
58 lines (51 loc) · 1.16 KB
/
signum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
Signum function -- https://en.wikipedia.org/wiki/Sign_function
"""
def signum(num: float) -> int:
"""
Applies signum function on the number
Custom test cases:
>>> signum(-10)
-1
>>> signum(10)
1
>>> signum(0)
0
>>> signum(-20.5)
-1
>>> signum(20.5)
1
>>> signum(-1e-6)
-1
>>> signum(1e-6)
1
>>> signum("Hello")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
>>> signum([])
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'list' and 'int'
"""
if num < 0:
return -1
return 1 if num else 0
def test_signum() -> None:
"""
Tests the signum function
>>> test_signum()
"""
assert signum(5) == 1
assert signum(-5) == -1
assert signum(0) == 0
assert signum(10.5) == 1
assert signum(-10.5) == -1
assert signum(1e-6) == 1
assert signum(-1e-6) == -1
assert signum(123456789) == 1
assert signum(-123456789) == -1
if __name__ == "__main__":
print(signum(12))
print(signum(-12))
print(signum(0))