Python - 基础知识3
2016-05-19 23:28
531 查看
1. 迭代器:
__metaclass__ = type
class Fibs(list): #斐波那契序列
def
__init__(self):
self.a = 0
self.b = 1
def
next(self):
self.a, self.b = self.b, self.a+self.b
return self.a
def
__iter__(self):
return self
fb = Fibs()
print fb.next()
ti = iter(fb) #iter是迭代器
for t in ti:
if t >
100: break
else: print
t
2. 生成器:
def flatten(lis):
for sublist
in lis:
for ele in sublist:
yield ele+1
lis = [[1,2,3], [4,5], [1,2]]
for temp in flatten(lis):
print temp,
#每次调用了lis.next()+1
print
def close(self):
try:
self.throw(GeneratorExit)
except
(GeneratorExit, StopIteration):
pass
else:
raise RuntimeError("Generator ignored GeneratorExit")
def func():
print
"Benson learning",
m = yield 10
#Generator
print
m
n = yield
12
print
n
print "My
test Generator"
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):
try:
try: lis+'' #如果是序列会引发异常, 跳到TypeError: pass
except TypeError: pass #序列就要递归所以pass
else: #如果不是序列(字符串虽然是序列,但是也不递归处理)
print "type"
raise TypeError #引发TypeError异常, 跳到yield lis
print lis
for sublist in lis:
for ele in flatten(sublist): #递归处理序列
yield ele
except
TypeError: #非序列和字符串使用生成器
yield 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):
nextY =
len(state)
for i in
range(nextY):
if abs(state[i]-nextX) in (0, nextY-i):
return True
return
False
def queens(num = 8, state = ()):
for pos in
range(num):
if not conflict(state, pos):
if len(state) == num-1:
yield (pos,)
else:
for result in queens(num, state + (pos,)):
yield (pos,)+result
def prettyprint(solution):
def
line(pos, length = len(solution)):
return '. '*(pos) + 'X ' + '. '*(length-pos-1)
for pos in
solution:
print line(pos)
import random
prettyprint( random.choice(list(queens(8))) )
__metaclass__ = type
class Fibs(list): #斐波那契序列
def
__init__(self):
self.a = 0
self.b = 1
def
next(self):
self.a, self.b = self.b, self.a+self.b
return self.a
def
__iter__(self):
return self
fb = Fibs()
print fb.next()
ti = iter(fb) #iter是迭代器
for t in ti:
if t >
100: break
else: print
t
2. 生成器:
def flatten(lis):
for sublist
in lis:
for ele in sublist:
yield ele+1
lis = [[1,2,3], [4,5], [1,2]]
for temp in flatten(lis):
print temp,
#每次调用了lis.next()+1
def close(self):
try:
self.throw(GeneratorExit)
except
(GeneratorExit, StopIteration):
pass
else:
raise RuntimeError("Generator ignored GeneratorExit")
def func():
"Benson learning",
m = yield 10
#Generator
m
n = yield
12
n
print "My
test Generator"
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):
try:
try: lis+'' #如果是序列会引发异常, 跳到TypeError: pass
except TypeError: pass #序列就要递归所以pass
else: #如果不是序列(字符串虽然是序列,但是也不递归处理)
print "type"
raise TypeError #引发TypeError异常, 跳到yield lis
print lis
for sublist in lis:
for ele in flatten(sublist): #递归处理序列
yield ele
except
TypeError: #非序列和字符串使用生成器
yield 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):
nextY =
len(state)
for i in
range(nextY):
if abs(state[i]-nextX) in (0, nextY-i):
return True
return
False
def queens(num = 8, state = ()):
for pos in
range(num):
if not conflict(state, pos):
if len(state) == num-1:
yield (pos,)
else:
for result in queens(num, state + (pos,)):
yield (pos,)+result
def prettyprint(solution):
def
line(pos, length = len(solution)):
return '. '*(pos) + 'X ' + '. '*(length-pos-1)
for pos in
solution:
print line(pos)
import random
prettyprint( random.choice(list(queens(8))) )
相关文章推荐
- Python - 基础知识1
- Python - 基础知识2
- ES使用脚本进行局部更新的排错记录 推荐
- python实现进度条--主要用在上传下载文件
- python实现进度条--主要用在上传下载文件
- python实现进度条--主要用在上传下载文件
- Python中文编码问题
- 机器学习笔记(一)朴素贝叶斯的Python代码实现
- Python处理多个客户端连接---线程服务器
- PySide——Python图形化界面入门教程(六)
- python中的行结构和缩进
- pycharm安装图解
- python的二维数组操作
- Python map reduce
- LeetCode Insertion Sort List
- LeetCode Word Break II
- Python中__name__=="__main__"的作用
- Python实战_2_第一周_第三节课程:真实世界中的网页解析
- 【Python】测算代码运行时间
- 机器学习算法与Python实践之(四)支持向量机(SVM)实现