zoukankan      html  css  js  c++  java
  • 第六题

    题目

    斐波那契数列

    my_code:
    def pei(num):
        a = [1,1];
        i = 2;
        if num <= 2:
            return a
        else:
            while i <= (num-1):
                a.append(a[i-1]+a[i-2]);
                i=i+1
            return a
    
    a = pei(int(input('please input the index of Fibonacci sequence: ')));
    print(a); 
    
    标准答案:
    1. 利用循环:
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    def fib(n):
        a,b = 1,1
        for i in range(n-1):
            a,b = b,a+b
        return a
     
    # 输出了第10个斐波那契数列
    print fib(10)
    
    1. 利用函数内部的递归:
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    # 使用递归
    def fib(n):
        if n==1 or n==2:
            return 1
        return fib(n-1)+fib(n-2)
     
    # 输出了第10个斐波那契数列
    print fib(10)
    
    总结

    自己的输出更为全面,输出指定索引的整个数列,而标准答案更为简洁,但是可读性降低,各有优势。

    为更美好的明天而战!!!
  • 相关阅读:
    HDU1251 统计难题
    字典树模板
    HDU5536 Chip Factory(01字典树)
    函数的返回值
    函数的使用原则
    文件修改
    函数
    文件内指针移动
    文件操作模式
    字符编码
  • 原文地址:https://www.cnblogs.com/lovely-bones/p/11624639.html
Copyright © 2011-2022 走看看