Skip to content

Commit 7fed6a1

Browse files
authored
Update and rename exponent_recursion.py to power_using_recursion.py
1 parent 7ec8e17 commit 7fed6a1

File tree

2 files changed

+36
-32
lines changed

2 files changed

+36
-32
lines changed

maths/exponent_recursion.py

Lines changed: 0 additions & 32 deletions
This file was deleted.

maths/power_using_recursion.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
== Raise base to the power of exponent using recursion ==
3+
Input -->
4+
Enter the base: 3
5+
Enter the exponent: 4
6+
Output -->
7+
3 to the power of 4: 81
8+
Inout -->
9+
Enter the base: 2
10+
Enter the exponent: 0
11+
Output -->
12+
2 to the power of 0: 1
13+
"""
14+
15+
16+
def power(base: int, exponent: int) -> float:
17+
"""
18+
power(3, 4)
19+
81
20+
>>> power(2, 0)
21+
1
22+
>>> all(power(base, exponent) == pow(base, exponent)
23+
... for base in range(-10, 10) for exponent in range(10))
24+
True
25+
"""
26+
return base * power(base, (exponent - 1)) if exponent else 1
27+
28+
29+
if __name__ == "__main__":
30+
print("Raise base to the power of exponent using recursion...")
31+
base = int(input("Enter the base: ").strip())
32+
exponent = int(input("Enter the exponent: ").strip())
33+
result = power(base, abs(exponent))
34+
if exponent < 0: # power() does not properly deal w/ negative exponents
35+
result = 1 / result
36+
print(f"{base} to the power of {exponent} is {result}"

0 commit comments

Comments
 (0)