From dfb4ce407497e549564c5181cfda33ee4f64843f Mon Sep 17 00:00:00 2001 From: Utsav Akash Naskar Date: Mon, 27 Jul 2020 15:03:13 +0530 Subject: [PATCH] Added Finding Exponent Program (#2238) * Finding Exponent Program * Build Error Fix - 1 * Build Error Fix - 2 * Error Fix - 1 datatype * self-documenting naming convension added * Update and rename exponent_recursion.py to power_using_recursion.py * Fix typo * Fix typo Co-authored-by: Christian Clauss --- maths/power_using_recursion.py | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 maths/power_using_recursion.py diff --git a/maths/power_using_recursion.py b/maths/power_using_recursion.py new file mode 100644 index 000000000..f82097f6d --- /dev/null +++ b/maths/power_using_recursion.py @@ -0,0 +1,36 @@ +""" +== 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 +""" + + +def power(base: int, exponent: int) -> float: + """ + 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 + """ + return base * power(base, (exponent - 1)) if exponent else 1 + + +if __name__ == "__main__": + 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)) + if exponent < 0: # power() does not properly deal w/ negative exponents + result = 1 / result + print(f"{base} to the power of {exponent} is {result}")