Last active
January 27, 2021 01:33
-
-
Save daduam/268eb564b451733ddca4ef9432bb4b2a to your computer and use it in GitHub Desktop.
Exponent function with recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytest | |
def power(a, n): | |
""" | |
power(base, exponent) | |
Returns the result of raising base to the power exponent. | |
Parameters: | |
a (int): The number to be multiplied exponent times | |
b (int): The non-negative exponent. A ValueError is thrown if b is negative | |
Returns: | |
int: a raised to the power b. | |
""" | |
if n < 0: | |
raise ValueError("second parameter should be non-negative") | |
if n == 0: | |
return 1 | |
return a * power(a, n - 1) | |
def test_exponent_zero(): | |
assert power(459, 0) == 1 | |
def test_negative_exponent(): | |
with pytest.raises(ValueError) as excinfo: | |
power(456, -1) | |
assert "non-negative" in str(excinfo.value) | |
def test_one_exponent_any_number_is_one(): | |
assert power(1, 435) == 1 | |
def test_a_exponent_one_is_a(): | |
a = 456 | |
assert power(a, 1) == a | |
def test_same_result_as_builtin_power(): | |
assert power(2, 45) == 2**45 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires pytest. Run tests with