您的位置:首页 > 编程语言 > Python开发

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))) )
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: