【问题标题】:Recursive sequence addition Python递归序列加法 Python
【发布时间】:2013-03-23 21:34:51
【问题描述】:

我有点卡住了。

我正在尝试计算移动不同尺寸齿轮的距离,以使它们彼此对齐。我认为它是某种递归调用,但我不知道如何编写它。 我有一个按齿轮顺序排列的半径列表

radiusList=[6,16,14,20,24,28]

所以一档 = 移动距离 = 0
二档移动距离 = 0 + 6 + 16
三档=0 +6 + 16 +16 + 14
第 4 档 = 0 +6 + 16 + 16 + 14 + 14 + 20
5 档 = 0 +6 + 16 + 16 + 14 + 14 + 20, +20 ,+ 24
6 档 = 0 +6 + 16 + 16 + 14 + 14 + 20、+20 、+ 24 + 24 +28 等...

另一件事是我需要更新它——现在对半径大小和齿轮数量很重要。但是我不知道如何处理它。 任何帮助将不胜感激。谢谢你。

更新:谢谢大家,我最后写了这样的东西。不过看起来有点啰嗦。

def createmovesequence():
if numberofcogs == 0 :
    void
if numberofcogs == 1:
    newmovelist.append(0)
if numberofcogs == 2:
    newmovelist.append(0)
    newmovelist.append(radiusList[0])
    newmovelist.append(radiusList[1])
if numberofcogs >= 3:
    newmovelist.append(0)
    newmovelist.append(radiusList[0])
    #newmovelist.append(radiusList[1])
    for i in range(2, len(radiusList)):
        newmovelist.append(radiusList[i-1])
        newmovelist.append(radiusList[i-1])
    newmovelist.append(radiusList[-1])    

# elif numberofcogs != len(radiusList): # 打印'错误'
打印新移动列表

createmovesequence()

我唯一的另一个想法是类似于带有大量 if 语句的 for 循环...

【问题讨论】:

    标签: python recursion for-loop


    【解决方案1】:
    def dist(n, radiusList):
      if n <= 1:
        return 0
      return dist(n-1, radiusList) + radiusList[n-1] + radiusList[n-2]
    

    【讨论】:

    • 第二次调用 dist 应该有 2 个参数。无论如何,它给出了错误的答案。
    【解决方案2】:

    这是一个有趣的问题。这是一个没有递归的解决方案:

    >>> gears = [6,16,14,20,24,28] 
    
    >>> def distance(n, radius):
    ...    return sum(gears[:n] + gears[1:n-1])
    
    >>> distance(1, gears) == 6
    True
    
    >>> distance(2, gears) == 6 + 16
    True
    
    >>> distance(3, gears) == 6 + 16 + 16 + 14
    True
    
    >>> distance(4, gears) == 6 + 16 + 16 + 14 + 14 + 20
    True
    

    【讨论】:

      【解决方案3】:

      你可能想看到的循环是:

      gear = 4    # which gear
      total = 0   # distance. we start from zero
      
      # for each idx such that 0 <= idx < gear…
      for idx in xrange(gear):
          total += radiusList[idx]
          total += radiusList[idx+1]
      

      注意在gear = 0 的情况下循环如何不执行任何操作(因为没有小于零但至少等于零的数字)。这可能是最明确的表示法,但是 hcalves 的表示法更短,学习它也会对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-05
        • 2019-05-13
        • 2023-03-21
        • 1970-01-01
        • 2010-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多