Skip to content

Commit 92f1cd7

Browse files
committed
Python abs() - Supplementing Materials
1 parent 05d5fc6 commit 92f1cd7

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-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+
Supplementing materials for the [tutorial on absolute values](https://realpython.com/python-absolute-value/) hosted on Real Python.
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import math
2+
from decimal import Decimal
3+
from fractions import Fraction
4+
from math import sqrt
5+
6+
7+
class Vector1:
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 Vector2:
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_value1(x):
25+
if x >= 0:
26+
return x
27+
else:
28+
return -x
29+
30+
31+
def absolute_value2(x):
32+
return x if x >= 0 else -x
33+
34+
35+
def absolute_value3(x):
36+
return sqrt(pow(x, 2))
37+
38+
39+
def absolute_value4(x):
40+
return (x**2) ** 0.5
41+
42+
43+
def absolute_value5(x):
44+
return float(str(x).replace("-", ""))
45+
46+
47+
if __name__ == "__main__":
48+
print(f"{absolute_value1(-12) = }")
49+
print(f"{absolute_value2(-12) = }")
50+
print(f"{absolute_value3(-12) = }")
51+
print(f"{absolute_value4(-12) = }")
52+
print(f"{absolute_value5(-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(Vector1(0.42, 1.5, 0.87)) = }")
61+
print(f"{abs(Vector2(0.42, 1.5, 0.87)) = }")
62+

0 commit comments

Comments
 (0)