【问题标题】:Sum sequence recursive in Python在 Python 中递归求和序列
【发布时间】:2020-09-25 07:07:18
【问题描述】:

我正在实现一个递归代码来对序列求和:x + x^2 / 2 + x^3 / 3... + x^n / n,我认为一个组合两个递归函数的设置,但正在返回n = 4 的值非常高,显然是不正确的,但这是我认为的最佳定义。代码如下:

def pot(x, n):
    if n == 0: return 1
    else:
        return x * pot(x, n - 1)

def Sum_Seq (x, n): 
    if n == 1: return x 
    else: 
        return x + Sum_Seq(pot(x, n - 1), n - 1) / (n - 1)

【问题讨论】:

标签: python python-3.x recursion


【解决方案1】:

如果递归是你的意思而不是你的目标,你可以使用这个函数:

def polynom(x,n_max):
    return sum(pow(x,n)*1./n for n in range(1, n_max + 1))

然后你得到你想要的:

x = 1
for i in range(5):
    print polynom(x,i)
Out:
    0
    1.0
    1.5
    1.83333333333
    2.08333333333

【讨论】:

    【解决方案2】:

    事实上,我不明白为什么在这种情况下需要两个递归函数。只需使用x**n 计算x 的幂n

    def sum_seq(x, n):
        if n == 1:
            return x
        else:
            return (x**n/n) + sum_seq(x, n-1)
    

    这在 Python 3 中效果很好:

    >>> power(10, 6)
    Out[1]: 189560.0
    

    请记住,在 Python 2 中,/ 运算符将推断您是在进行整数除法还是浮点除法。为了保证您的除法将是 Python 2 中的浮点除法,只需从 Python 3 导入 / 运算符:

    from __future__ import division
    

    甚至将您的部门设为浮动:

    float(x**n)/n
    

    【讨论】:

      【解决方案3】:

      你的Sum_Seq() 函数应该是这样的:

      def Sum_Seq (x, n): 
          if n == 1: 
              return x 
          else: 
              return pot(x, n)*1.0/n + Sum_Seq(x, n-1) # 1.0 is used for getting output as a fractional value.
      

      注意:您不需要需要让另一个递归函数计算功率。在 python 中,你可以通过 x**n 得到 x 的 n 次幂。

      【讨论】:

        【解决方案4】:

        您的pot 函数似乎执行** power operator 的工作。

        也许这样的事情会有所帮助 -

        In [1]: # x + x^2 / 2 + x^3 / 3... + x^n / n
        
        In [2]: def sum_seq(x, n):
           ...:     if n <= 0:
           ...:         return 0
           ...:     return (x**n)/n + sum_seq(x, n - 1)
           ...:
        
        In [3]: sum_seq(10, 2)
        Out[3]: 60.0
        

        编辑: 我认为您的代码中错误结果的原因是这一行 -

        return x + Sum_Seq(pot(x, n - 1), n - 1) / (n - 1)

        Sum_Seq 添加到 x,不遵循您提到的模式

        【讨论】:

          【解决方案5】:

          相反,您可以使用简单的线性递归方法

          def lin_sum(s,n):
          
              if n==0:
                  return 0
              else:
                  return lin_sum(s,n-1)+s[n-1]
          s=[1,2,3,4,5]    
          print(lin_sum(s,5))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-03-23
            • 1970-01-01
            • 2010-12-05
            相关资源
            最近更新 更多