Skip to content

Commit 2538933

Browse files
authored
Merge pull request #282 from realpython/python-absolute-value
Python abs() - Supplemental Materials
2 parents 05d5fc6 + 5a447a5 commit 2538933

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

python-absolute-value/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# How to Find an Absolute Value in Python
2+
3+
Supplemental materials for the [tutorial on absolute values](https://realpython.com/python-absolute-value/) hosted on Real Python.
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import math
2+
from decimal import Decimal
3+
from fractions import Fraction
4+
from math import sqrt
5+
6+
7+
class VectorBound:
8+
def __init__(self, *coordinates):
9+
self.coordinates = coordinates
10+
11+
def __abs__(self):
12+
origin = [0] * len(self.coordinates)
13+
return math.dist(origin, self.coordinates)
14+
15+
16+
class VectorFree:
17+
def __init__(self, *coordinates):
18+
self.coordinates = coordinates
19+
20+
def __abs__(self):
21+
return math.hypot(*self.coordinates)
22+
23+
24+
def absolute_value_piecewise(x):
25+
if x >= 0:
26+
return x
27+
else:
28+
return -x
29+
30+
31+
def absolute_value_piecewise_conditional_expression(x):
32+
return x if x >= 0 else -x
33+
34+
35+
def absolute_value_algebraic(x):
36+
return sqrt(pow(x, 2))
37+
38+
39+
def absolute_value_algebraic_exponents(x):
40+
return (x**2) ** 0.5
41+
42+
43+
def absolute_value_silly(x):
44+
return float(str(x).replace("-", ""))
45+
46+
47+
if __name__ == "__main__":
48+
print(f"{absolute_value_piecewise(-12) = }")
49+
print(f"{absolute_value_piecewise_conditional_expression(-12) = }")
50+
print(f"{absolute_value_algebraic(-12) = }")
51+
print(f"{absolute_value_algebraic_exponents(-12) = }")
52+
print(f"{absolute_value_silly(-12) = }")
53+
54+
print(f"{abs(-12) = }")
55+
print(f"{abs(-12.0) = }")
56+
print(f"{abs(complex(3, 2)) = }")
57+
print(f"{abs(Fraction('-3/4')) = }")
58+
print(f"{abs(Decimal('-0.75')) = }")
59+
60+
print(f"{abs(VectorBound(0.42, 1.5, 0.87)) = }")
61+
print(f"{abs(VectorFree(0.42, 1.5, 0.87)) = }")

0 commit comments

Comments
 (0)