Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathpower_using_recursion.py
More file actions
Latest commit
63 lines (57 loc) · 1.65 KB
/
Copy pathpower_using_recursion.py
File metadata and controls
63 lines (57 loc) · 1.65 KB
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
59
60
61
62
63
"""
== Raise base to the power of exponent using recursion ==
Input -->
Enter the base: 3
Enter the exponent: 4
Output -->
3 to the power of 4 is 81
Input -->
Enter the base: 2
Enter the exponent: 0
Output -->
2 to the power of 0 is 1
"""
defpower(base: int, exponent: int) ->float:
"""
Calculate the power of a base raised to an exponent.
>>> power(3, 4)
81
>>> power(2, 0)
1
>>> all(power(base, exponent) == pow(base, exponent)
... for base in range(-10, 10) for exponent in range(10))
True
>>> power('a', 1)
'a'
>>> power('a', 2)
Traceback (most recent call last):
...
TypeError: can't multiply sequence by non-int of type 'str'
>>> power('a', 'b')
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> power(2, -1)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded
>>> power(0, 0)
1
>>> power(0, 1)
0
>>> power(5,6)
15625
>>> power(23, 12)
21914624432020321
"""
returnbase*power(base, (exponent-1)) ifexponentelse1
if__name__=="__main__":
fromdoctestimporttestmod
testmod()
print("Raise base to the power of exponent using recursion...")
base=int(input("Enter the base: ").strip())
exponent=int(input("Enter the exponent: ").strip())
result=power(base, abs(exponent))
ifexponent<0: # power() does not properly deal w/ negative exponents
result=1/result
print(f"{base} to the power of {exponent} is {result}")