Skip to content

Commit 1b86189

Browse files
committed
Added iterative solution for power calculation fixes #12709
1 parent ee3f4be commit 1b86189

1 file changed

Lines changed: 18 additions & 5 deletions

File tree

maths/power_using_iteration.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,25 @@ def power(base: float, exponent: int) -> float:
2828
-8.0
2929
>>> power(0, 5)
3030
0.0
31-
>>> power(0, 0)
32-
1.0
31+
>>> power(0, 1)
32+
0.0
3333
>>> power(0, -1)
3434
Traceback (most recent call last):
3535
...
3636
ZeroDivisionError: 0.0 cannot be raised to a negative power.
37+
>>> power(0, 0)
38+
Traceback (most recent call last):
39+
...
40+
ValueError: 0.0 raised to the power of 0 is indeterminate.
3741
>>> power(1, 1000)
3842
1.0
3943
4044
"""
45+
if base == 0 and exponent == 0:
46+
raise ValueError("0.0 raised to the power of 0 is indeterminate.")
47+
if base == 0 and exponent < 0:
48+
raise ZeroDivisionError("0.0 cannot be raised to a negative power.")
49+
4150
result = 1.0
4251
if exponent < 0:
4352
base = 1 / base
@@ -51,6 +60,7 @@ def power(base: float, exponent: int) -> float:
5160

5261

5362
if __name__ == "__main__":
63+
5464
import doctest
5565
doctest.testmod()
5666
print("Raise base to the power of exponent using an optimized approach...")
@@ -68,6 +78,9 @@ def power(base: float, exponent: int) -> float:
6878
# Display the result
6979
print(f"{base} to the power of {exponent} is {result}")
7080

71-
except ValueError:
72-
# Handle invalid input
73-
print("Invalid input! Please enter numeric values for base and exponent.")
81+
except ValueError as e:
82+
# Handle invalid input or indeterminate cases
83+
print(e)
84+
except ZeroDivisionError as e:
85+
# Handle division by zero
86+
print(e)

0 commit comments

Comments
 (0)