`
ay_guobo
  • 浏览: 116851 次
  • 性别: Icon_minigender_1
  • 来自: 札幌
社区版块
存档分类
最新评论

菜鸟学Python - 斐波那契数列(二)

 
阅读更多

上一次我们写了一个关于斐波那契数列的程序,为了提高对Python的灵活运用,这次再写一个小程序。
大家可以比较一下每个程序的优势,看看是否得到什么灵感。

01 import sys
02 
03 # Here's our main function. Python is pretty efficient here. You
04 # should notice that there are no braces. Python is dependant on
05 # whitespace to define blocks.
06 
07 def main():
08   print "\nHow many numbers of the sequence would you like?"
09   n = int(sys.stdin.readline())
10   fibonacci(n)
11 
12 # Here's the fibonacci function. Like in Perl, you can assign multiple
13 # variables on a line without using a temporary variable. Also, the for 
14 # loop here works more like a foreach loop by setting a range from 0 to n.
15 
16 def fibonacci(n):
17   a,b = 0,1
18   for i in range(0,n):
19     print a
20     a,b, = b,a+b
21 
22 main()

菜鸟学Python - 斐波那契数列(Fibonacci)- 续(一) - 梦想社 - 梦想社两个函数实现了这个算法:
1、main函数主要是获取用户输入,并执行程序。
2、fibonacci函数就是主要的算法实现了。
3、大家关键是看看程序的第20行,这个是程序的亮点。
如果是java呢?
0
1
分享到:
评论
2 楼 ay_guobo 2011-10-30  
mirguest 写道
给楼主一个更牛的:
def fib( ):
    ''' Unbounded generator for Fibonacci numbers '''
    x, y = 0, 1
    while True:
        yield x
        x, y = y, x + y
if __name__ == "__main__":
    import itertools
    print list(itertools.islice(fib( ), 10))

谢谢哈

不错不错,但是对于我这菜鸟来说 itertools 很少用 学习了

startNumber = int(raw_input("Enter the start number here "))
endNumber = int(raw_input("Enter the end number here "))

def fib(n):
    if n < 2:
        return n
    return fib(n-2) + fib(n-1)

map(fib, range(startNumber, endNumber))

这个怎么样
1 楼 mirguest 2011-10-30  
给楼主一个更牛的:
def fib( ):
    ''' Unbounded generator for Fibonacci numbers '''
    x, y = 0, 1
    while True:
        yield x
        x, y = y, x + y
if __name__ == "__main__":
    import itertools
    print list(itertools.islice(fib( ), 10))

相关推荐

    Python3入门经典100例菜鸟教程21-30题.pdf

    4. **数列通项与前N项和**:斐波那契数列是一个经典的数列问题。题目中的数列是斐波那契数列的一个变种,每一项的分子是前两项的和,分母是前一项的分子。通过定义三个变量,分别存储当前分母、当前分子和上一步的...

    菜鸟经典python100例.docx

    在第六个问题中,我们需要实现斐波那契数列的计算。这个问题可以使用 Python 的递归函数和循环语句来解决。 程序代码: ``` def fbnq(n): if n == 1: return [1] if n == 2: return [1, 1] fbnqs = [1, 1] ...

    Python从菜鸟到大神的100道经典练习题(附答案)Python练手小程序最新版本

    Python从菜鸟到大神的100道经典练习题是一个Python100道基础⼊门练习题,包含了大部分Python入门级别的习题,还有习题答案。希望通过这100道例题,能对python3的基础代码能力有一定的掌握。另外包含练手小程序源码,...

    Python3 菜鸟查询手册

    目录: 01 教程.png 01.01 2.x与3.x版本区别.png 02 基础语法.png 02.01 命令行参数.png ... 25.26 使用递归斐波那契数列.png 25.27 文件 IO.png 25.28 字符串判断.png 25.29 字符串大小写转换.png ...

    Python技术速查手册.docx

    - **在线教程**:菜鸟教程(https://www.runoob.com/python/python-tutorial.html)、W3School(https://www.w3school.com.cn/python/)等。 - **书籍**:《Python编程:从入门到实践》、《流畅的Python》等。 ...

Global site tag (gtag.js) - Google Analytics