python学习笔记2--初学递归函数 - Go语言中文社区

python学习笔记2--初学递归函数


递归,即自己调用自己。在比较少调用就能达到目的,或者不用递归实在不好表达时使用。
例如:fibonacci数列,可以表示为:
def fibonacci(n):
    result = 0
    if n == 1:
        result = 1
    elif n == 2:
        result = 2
    else:
        result = fibonacci(n - 2) + fibonacci(n - 1)
    return result
计算较小的数字时速度还可以,如果是projecteuler.net的第二题Even Fibonacci numbers:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms
用递归的方法,运行起来会花费好几秒,而且如果数字再大一些程序的可用空间就会爆掉。但用一个while循环不到1秒就能解决了。这个可以等以后学了数据结构或者算法神马的时候再深入了解一下时间、空间复杂度,或者看有没有其他方法。
a = 1
b = 1
c = a + b
s = 0
while b < 4000000:
    s += c
    a = b + c
    b = c + a
    c = a + b
print (s)
《像计算机科学家一样思考python》第五章习题中的画科赫曲线,除了递归还真不知道应该怎么做:

import turtle

def koch(t, x):
    if x < 5:
        t.fd(x)
    else:
        l = x / 3
        koch(t, l)
        t.lt(60)
        koch(t, l)
        t.rt(120)
        koch(t, l)
        t.lt(60)
        koch(t, l)

length = float(input("请输入曲线长度:"))
bob = turtle.Turtle()
bob.pu()
bob.bk(length / 2)
bob.pd()
bob.speed(0)
koch(bob, length)
turtle.mainloop()

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/giftdawn/article/details/50217281
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-08 10:12:32
  • 阅读 ( 1010 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢