标签:style blog http color os 使用 io strong for
什么是迭代呢?和递归又有什么区别呢?
根据维基百科和网上的资料:
迭代:迭代是重复反馈过程的活动,其目的通常是为了接近并到达所需的目标或结果。每一次对过程的重复被称为一次“迭代”,
而每一次迭代得到的结果会被用来作为下一次迭代的初始值。
如求1+2+3+4+5的和:
递归呢?指在函数的定义中使用函数自身的方法。也就是函数不停的调用自己直到满足一定条件。
而用递归是怎样求1--5的和呢?
斐波那契数列的递归和迭代实现:
1 def fib(n): 2 if n>0: 3 if (n==1 or n==2): 4 return 1 5 else: 6 return fib(n-1)+fib(n-2) 7 else: 8 return -1 9 def fib_2(n): 10 if n<=0: 11 return -1 12 else: 13 a=1 14 b=1 15 s=1 16 for i in range(n-2): 17 s=a+b 18 a=b 19 b=s 20 return s 21 print fib(int(raw_input(‘Please input a number you want to calculate the fib number:‘))) 22 print fib_2(int(raw_input(‘Please input a number you want to calculate the fib number:‘)))
从左往右扫描对象的方式都是可迭代的。
如何判断一个对象是不是可迭代的呢?
stackoverflow是这么说的。http://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable
2. 使用collections模块的Iterable类型来判断
1 capitals={‘China‘:‘beijing‘,‘America‘:‘Washington‘,‘Russia‘:‘Moscow‘} 2 print ‘countries:‘ 3 for country in capitals: 4 print country 5 print ‘capitals:‘ 6 for capital in capitals.itervalues(): 7 print capital
可以看出字典进行迭代操作时,得出的值不一定按顺序。
标签:style blog http color os 使用 io strong for
原文地址:http://www.cnblogs.com/JohnTsai/p/3936267.html