def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while b < n: print(b) a, b = b, a+b >>>fib(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 我们可以编写一个函数来生成有给
1,2,3,5,8,13..... 求第n个数 def get_num(n): if n == 1: return 1 if n == 2: return 2 return get_num(n - 1) + get_num(n - 2) def get_num(n): if n == 1: return 1 if n == 2: return 2 a = 1 b = 2 for i in range(n - 2): a, b = b, a + b return b分为递归和循环两个求法
一.生成器(generator) 先来看看一个简单的菲波那切数列,出第一个和第二个外,任意一个数都是由前两个数相加得到的.如:0,1,1,2,3,5,8,13...... 输入斐波那契数列前N个数: def fab(max): n, a, b = 0, 0, 1 while n < max: print b a, b = b, a + b n = n + 1 结果: >>> fib(100) 1 1 2 3 5 8 13 但是,要提高 fib 函数的可复用性,最好不要直接打印出数列
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 斐波那契数列求和 { class Program { static void Main(string[] args) { Console.WriteLine()); Console.WriteLine()); Console.WriteLine()