将x幂n的解减为双

时间:2019-04-04 08:08:41

标签: python

我试图解决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]
  •   

我的解决方案和TestCase

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值?

1 个答案:

答案 0 :(得分:1)

在奇怪的情况下,您不会返回任何内容,只是分配

result *= x

将其更改为:

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