Improve power.py (#12567)

* Fix And Add power.py

To fix the inaccuracies and allow handling of negative exponents and bases, the key issue lies in how negative numbers are handled in the power calculation, especially when dividing.
## Example Output:
```python
>>> power(4, 6)
4096
>>> power(2, 3)
8
>>> power(-2, 3)
-8
>>> power(2, -3)
0.125
>>> power(-2, -3)
-0.125
```

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update power.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update power.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update power.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update power.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
This commit is contained in:
lighting9999 2025-02-10 01:51:18 +08:00 committed by GitHub
parent e59d819d09
commit 338cbafe0d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,4 +1,4 @@
def actual_power(a: int, b: int):
def actual_power(a: int, b: int) -> int:
"""
Function using divide and conquer to calculate a^b.
It only works for integer a,b.
@ -19,10 +19,12 @@ def actual_power(a: int, b: int):
"""
if b == 0:
return 1
half = actual_power(a, b // 2)
if (b % 2) == 0:
return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
return half * half
else:
return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
return a * half * half
def power(a: int, b: int) -> float:
@ -43,9 +45,9 @@ def power(a: int, b: int) -> float:
-0.125
"""
if b < 0:
return 1 / actual_power(a, b)
return 1 / actual_power(a, -b)
return actual_power(a, b)
if __name__ == "__main__":
print(power(-2, -3))
print(power(-2, -3)) # output -0.125