Python - 基础知识3

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))) )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值