可爱的 Python: 用基于生成器的状态机和协同程序增加效率
2007-03-29 12:05:22 来源:WEB开发网核心提示: 清单 2. stategen_test.pyfrom __future__ import generatorsimport sysdef math_gen(n):# Iterative function becomes a generatorfrom math import sinwhil
清单 2. stategen_test.py
from __future__ import generators
import sys
def math_gen(n): # Iterative function becomes a generator
from math import sin
while 1:
yield n
n = abs(sin(n))*31
# Jump targets not state-sensitive, only to simplify example
def jump_to(val):
if 0 <= val < 10: return 'ONES'
elif 10 <= val < 20: return 'TENS'
elif 20 <= val < 30: return 'TWENTIES'
else: return 'OUT_OF_RANGE'
def get_ones(iter):
global cargo
while 1:
print "
ONES State: ",
while jump_to(cargo)=='ONES':
print "@ %2.1f " % cargo,
cargo = iter.next()
yield (jump_to(cargo), cargo)
def get_tens(iter):
global cargo
while 1:
print "
TENS State: ",
while jump_to(cargo)=='TENS':
print "#%2.1f " % cargo,
cargo = iter.next()
yield (jump_to(cargo), cargo)
def get_twenties(iter):
global cargo
while 1:
print "
TWENTIES State: ",
while jump_to(cargo)=='TWENTIES':
print "*%2.1f " % cargo,
cargo = iter.next()
yield (jump_to(cargo), cargo)
def exit(iter):
jump = raw_input('
[co-routine for jump?] ').upper()
print "...Jumping into middle of", jump
yield (jump, iter.next())
print "
Exiting from exit()..."
sys.exit()
def scheduler(gendct, start):
global cargo
coroutine = start
while 1:
(coroutine, cargo) = gendct[coroutine].next()
if __name__ == "__main__":
num_stream = math_gen(1)
cargo = num_stream.next()
gendct = {'ONES' : get_ones(num_stream),
'TENS' : get_tens(num_stream),
'TWENTIES' : get_twenties(num_stream),
'OUT_OF_RANGE': exit(num_stream) }
scheduler(gendct, jump_to(cargo))
更多精彩
赞助商链接