2013-06-05 62 views
0

任何人都可以帮助将其转换为递归函数吗?将for循环转换为递归函数

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) 
+11

*为什么*迭代函数通常更好,而在蟒蛇时,就更是如此。您避免了递归限制和大量的函数调用开销。顺便说一下:在你的函数中,你正在混合计算和输入/输出。这是糟糕的设计。这两件事应该分开以提高代码的可重用性。 – Bakuriu

+0

谢谢,我的目标是抓住实现递归的思想/设计过程,所以这只是一个演示代码。 – 01dfaithfull

回答

0

要解决递归问题,需要用递归方式说明问题。这意味着以自我类似的方式来定义它。

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

  • 什么是加速度和速度后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) 
0

一个相当简单的方法:

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内容通过递归调用来更新。

+0

你的功能不返回任何东西 – oleg

+0

好评...已更新! – Emmanuel