1. 迭代器:
__metaclass__ = type
class Fibs(list): #斐波那契序列
fb = Fibs()
print fb.next()
ti = iter(fb) #iter是迭代器
for t in ti:
2. 生成器:
def flatten(lis):
lis = [[1,2,3], [4,5], [1,2]]
for temp in flatten(lis):
print
def close(self):
def func():
test = func()
a = test.next() #第一次运行到 m = yield 10 停下来, 返回了10
#test.send(None) #第一次调用生成器函数, 使用send(None) or next()
b = test.send("python!!!") # m = 'python!!!', 返回了12
print a, b #next() and send(...)返回yield的参数值
test2 = func()
close(test2)
test2.next()
d = test2.send('Python!!!')
下面是一个生成器的递归调用: (个人理解之后, 加深对生成器的了解)
# 生成器是惰性求值(lazy eval),一般在内存紧张的条件下使用
# 惰性求值多用于函数式编程中
def flatten(lis):
print list(flatten([ [[1],2], 3,4, [5, [6,7]], 8 ]))
print list(flatten(['abc', 'b', ['def'], 'ghi', 'a']))
'''结果:
[[[1], 2], 3, 4, [5, [6, 7]], 8]
[[1], 2]
[1]
1
2
3
4
[5, [6, 7]]
5
[6, 7]
6
7
8
[1, 2, 3, 4, 5, 6, 7, 8]
['abc', 'b', ['def'], 'ghi', 'a']
type
type
['def']
type
type
type
['abc', 'b', 'def', 'ghi', 'a']
'''
下面是书上的n皇后问题求解应用:(枚举求解)
def conflict(state, nextX):
def queens(num = 8, state = ()):
def prettyprint(solution):
import random
prettyprint( random.choice(list(queens(8))) )