forked from zhongyingqun/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfibonacci.py
More file actions
57 lines (50 loc) · 1.22 KB
/
fibonacci.py
File metadata and controls
57 lines (50 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# -*- encoding:utf-8 -*-
#fib=lambda n:1 if n<=2 else fib(n-1)+fib(n-2)
import time
previous = {1:1L, 2:1L}
def fib(n):
if previous.has_key(n):
return previous[n]
else:
newValue = fib(n-1) + fib(n-2)
previous[n] = newValue
return newValue
def fib1(max):
n, a, b = 0, 0, 1
list = []
while n < max:
list.append(b)
a, b = b , a+b
n += 1
return list[max-1]
#内存问题,如何能够使内存保持一个常数
class Fab(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1
def __iter__(self):
return self
def next(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a+self.b
self.n = self.n + 1
return r
raise StopIteration()
#for n in Fab(5):
# print n
#使用yield
def fib2(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a+b
n = n + 1
#for n in fib2(5):
# print n
if __name__ == '__main__':
#start = time.clock()
#import profile
#answer = fib1(50)
#end = time.clock()
#print answer