【问题标题】:Convert a for-loop to a recursive function将 for 循环转换为递归函数
【发布时间】:2013-05-31 16:39:23
【问题描述】:

谁能帮忙把它转换成递归函数?

def max_vel(t):
    vel = 0   
    thr = 10
    c = -0.1
    for i in range(t):
        fric = c * vel
        acc = thr + fric
        vel = vel + acc
        print fric, acc, vel
    print vel
    return vel
print max_vel(154)

【问题讨论】:

  • 为什么? 迭代函数通常更好,在 python 中尤其如此。您避免了递归限制和大量函数调用开销。顺便说一句:在您的函数中,您正在混合计算和输入/输出。这是一个糟糕的设计。这两件事应该分开以增加代码的可重用性。
  • 谢谢,我的目标是掌握实现递归的思想/设计过程,所以这只是一个演示代码。

标签: python function recursion iteration


【解决方案1】:

要解决递归问题,需要以递归方式陈述该问题。这意味着以自我相似的方式定义它。

在这种情况下,有变量:时间、加速度和速度。因此,必须用具有相同变量的子问题来定义主要问题。我们可以使用 2 个(非常相似的)问题:

  • 什么是从开始 t 秒后的加速度和速度。
  • 如果我们给出了加速度和速度,那么加速度和速度是多少? t 秒后的速度。

有两种(相似的)递归解决方案:

def start_av(t):
  if t == 0: return 0, 0
  acc, vel = start_av(t-1)
  thr = 10
  c = -0.1
  fric = c*vel
  acc = thr + fric
  return (acc, vel + acc)

def given_av(t, acc=0, vel=0):
  if t == 0: return acc, vel
  thr = 10
  c = -0.1
  fric = c*vel
  acc = thr + fric
  return given_av(t-1, acc, vel + acc)    

print start_av(10)
print given_av(10)

【讨论】:

    【解决方案2】:

    一个相当简单的方法:

    def max_vel(t, vel=[0], thr=10):
        c = -0.1
        if t > 0:
            fric = c * vel[0]
            acc = thr + fric
            vel[0] = vel[0] + acc
            print fric, acc, vel
            max_vel(t - 1, vel, thr)
        return vel[0]
    

    这里你只是递减t,因为这是迭代次数。 c 永远不会改变,所以它不会在递归中传递。现在我使用 vel 作为 1 个元素的列表,因为在 Python 中列表是可变的:这允许通过递归调用更新 vel 内容。

    【讨论】:

    • 你的函数没有返回任何东西
    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 2017-10-26
    相关资源
    最近更新 更多