- 論壇徽章:
- 0
|
本帖最后由 hp_truth 于 2011-03-01 15:42 編輯
剛開(kāi)始學(xué)python,看python基礎(chǔ)教程那本書,被里面的yield弄暈了。
里面提到用yield解決八皇后問(wèn)題, 人家好像都講明白了,就是自己理解起來(lái)有點(diǎn)困難。
后來(lái)還是通過(guò)對(duì)比以前的方法來(lái)理解yield, 稍微好點(diǎn)了。- #! /usr/bin/env python
- __metaclass__ = type
- # 判斷沖突的函數(shù)
- 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 queen1(num = 8, state = ()):
- for pos in range(num):
- if not conflict(state, pos):
- if len(state) == num -1:
- yield (pos,)
- else:
- for i in queen1(num, state + (pos,)):
- yield i + (pos,)
- # 以前用過(guò)的方法
- sum=[]
- def queen2(num, result = []):
- if len(result) == num:
- sum.append(result)
- else:
- for pos in range(num):
- if not conflict(result, pos):
- queen2(num, result + [pos])
- # 參照以前的方法, 對(duì)書上的方法稍微改了一下
- # 比書上的方法多了幾次函數(shù)調(diào)用, 主要是體驗(yàn)一下
- # 遞歸調(diào)用中用到了幾次yield, 但對(duì)外界來(lái)說(shuō),
- # 應(yīng)該是 ‘yield i + [pos] 這 一句是真正的返回一種八皇后方案。
- # 而‘yield []’只是內(nèi)部遞歸調(diào)用時(shí)返回。
- def queen3(num, result = []):
- if len(result) == num:
- yield []
- else:
- for pos in range(num):
- if not conflict(result, pos):
- for i in queen3(num, result + [pos]):
- yield i + [pos]
- def prettyprint(solution):
- def line(pos, length=len(solution)):
- return '. ' * (pos) + 'X ' + '. ' * (length-pos-1)
- for pos in solution:
- print line(pos)
- import random
- print len(list(queen1( 8 )))
- prettyprint(random.choice(list(queen1( 8 ))))
- queen2( 8 )
- print len(list(sum))
- prettyprint(random.choice(list(sum)))
- print len(list(queen3( 8 )))
- prettyprint(random.choice(list(queen3( 8 ))))
- i = queen3( 8 )
- print i.next()
復(fù)制代碼 |
|