递归序列加法Python

2024-05-23 22:12:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点卡住了。在

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

半径列表=[6,16,14,20,24,28]

所以1档=移动距离=0
距离br+0+2档移动 3档=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!=长度(半径列表): #打印“错误”
打印newmovelist

创建移动序列()

我唯一的另一个想法是在for循环中使用大量if语句。。。在


Tags: br距离列表for数量if尺寸def
3条回答
def dist(n, radiusList):
  if n <= 1:
    return 0
  return dist(n-1, radiusList) + radiusList[n-1] + radiusList[n-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

您可能希望看到的循环是:

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]

注意在case gear = 0中循环是如何不做任何事情的(因为没有这样的数字会小于零,但至少等于零)。这可能是最明确的表示法,但hcalves的一个比较短,学习它对你也有帮助。在

相关问题 更多 >