亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区
Chinaunix
標(biāo)題:
被yield弄暈了
[打印本頁]
作者:
hp_truth
時(shí)間:
2011-03-01 15:40
標(biāo)題:
被yield弄暈了
本帖最后由 hp_truth 于 2011-03-01 15:42 編輯
剛開始學(xué)python,看python基礎(chǔ)教程那本書,被里面的yield弄暈了。
里面提到用yield解決八皇后問題, 人家好像都講明白了,就是自己理解起來有點(diǎn)困難。
后來還是通過對(duì)比以前的方法來理解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,)
# 以前用過的方法
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ì)外界來說,
# 應(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ù)制代碼
作者:
ttvast
時(shí)間:
2011-03-02 21:27
不用
沒用
從來不用,還是一樣用python寫程序
作者:
hp_truth
時(shí)間:
2011-03-03 13:25
回復(fù)
2#
ttvast
赫赫,是嗎, 還是有用的, 不然干嘛提出這么個(gè)概念。 目前只知道當(dāng)需要生成大量數(shù)據(jù)的時(shí)候, 可以用yield, 減少內(nèi)存占用量, 其他的應(yīng)用還有待進(jìn)一步學(xué)習(xí)
)
歡迎光臨 Chinaunix (http://www.72891.cn/)
Powered by Discuz! X3.2