Skip to content

Power using recursion: correctly implemented recursion #5050

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions maths/power_using_recursion.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"""


def power(base: int, exponent: int) -> float:
def power(base: int, exponent: int) -> int:
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a test for 0^0?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But I removed the check for 0^0 since the testing suite expected it to return 1, which math.pow does

Copy link
Member

@poyea poyea Oct 6, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may reference those fast exp in the same folder and see what are their behaviour. It's still ok to add tests for this function.

power(3, 4)
81
Expand All @@ -23,7 +23,14 @@ def power(base: int, exponent: int) -> float:
... for base in range(-10, 10) for exponent in range(10))
True
"""
return base * power(base, (exponent - 1)) if exponent else 1
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this works for 0^0.

if exponent == 0:
return 1
if exponent == 1:
return base
if exponent % 2 == 0:
return power(base * base, exponent // 2)
else:
return base * power(base * base, (exponent - 1) // 2)


if __name__ == "__main__":
Expand All @@ -32,5 +39,5 @@ def power(base: int, exponent: int) -> float:
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
result = 1.0 / result
print(f"{base} to the power of {exponent} is {result}")