python - 将 x 幂 n 的解加倍减少
问题描述
我试图解决 leetcode 中的一个 pow(x, n) 问题
实现pow( x , n ),它计算x的n (xn) 次幂。
示例 1:
Input: 2.00000, 10 Output: 1024.00000
示例 2:
Input: 2.10000, 3 Output: 9.26100
示例 3:
Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25
笔记:
- -100.0 < x < 100.0
- n是一个 32 位有符号整数,在 [−231, 231 − 1] 范围内
我的解决方案和测试用例
import unittest
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s")
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
if n < 0:
return 1 /self.myPow(x, -n)
else:
partial = self.myPow(x, n//2)
logging.debug(f"partial: {partial}")
result = partial * partial
if n % 2 == 1: #odd
result *= x
else: #even
return result
class MyCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def test_1(self):
x = 2
n = 10
answer = 1024
check = self.solution.myPow(x, n)
self.assertEqual(check, answer)
unittest.main()
它报告错误
In [3]: !python 50.powerxn.py
DEBUG partial: 1
DEBUG partial: None
E
======================================================================
ERROR: test_1 (__main__.MyCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "50.powerxn.py", line 32, in test_1
check = self.solution.myPow(x, n)
File "50.powerxn.py", line 16, in myPow
partial = self.myPow(x, n//2)
File "50.powerxn.py", line 16, in myPow
partial = self.myPow(x, n//2)
File "50.powerxn.py", line 18, in myPow
result = partial * partial
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
我不明白为什么 partial 会得到 None 值?
解决方案
在奇怪的情况下你没有返回任何东西,你只是分配
result *= x
将其更改为:
if n % 2 == 1: #odd
return result * x
else: #even
return result
推荐阅读
- python - 如何使用 Cartopy 更新 GeoAxes 的投影?
- javascript - 光滑的滑块圆形进度条箭头
- node.js - 使用 QnA Maker 服务的 Azure 机器人不会在 Slack 的线程中回复
- pandas-groupby - Pandas 对按另一列分组的行求和
- c# - Selenium c#检查::before是否在跨度内可用
- android - React 本机 F2 图表未显示在 android 上
- sql - 在sql中的范围之间进行选择
- java - Java AudioSystem prevent loop from repeating before song finishes
- c# - 如何隐藏构建和运行的一些元素(脏项目和解决方案)
- python - 可视化 ffmpeg 基准