Python x次方n的双约化解

Python x次方n的双约化解,python,Python,我试图解决leetcode中的一个pow(x,n)问题 机具,计算提升到n(xn)幂的x 示例1: Input: 2.00000, 10 Output: 1024.00000 Input: 2.10000, 3 Output: 9.26100 Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 示例2: Input: 2.00000, 10 Output: 1024.00000 Input: 2.

我试图解决leetcode中的一个pow(x,n)问题

机具,计算提升到n(xn)幂的x

示例1:

Input: 2.00000, 10
Output: 1024.00000
Input: 2.10000, 3
Output: 9.26100
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
示例2:

Input: 2.00000, 10
Output: 1024.00000
Input: 2.10000, 3
Output: 9.26100
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
示例3:

Input: 2.00000, 10
Output: 1024.00000
Input: 2.10000, 3
Output: 9.26100
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
注意:

Input: 2.00000, 10
Output: 1024.00000
Input: 2.10000, 3
Output: 9.26100
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
  • -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()

我不明白为什么partial会得到一个None值?

在奇数情况下,您没有返回任何内容,只是赋值

result *= x
将其更改为:

if n % 2 == 1: #odd
    return result * x
else: #even 
    return result

n
为奇数时,您不返回任何内容,您只需分配给
result
。发生这种情况是因为您没有返回任何内容。