码迷,mamicode.com
首页 > 编程语言 > 详细

python 逻辑推理编程解决八皇后

时间:2014-07-19 23:31:49      阅读:377      评论:0      收藏:0      [点我收藏+]

标签:python   八皇后   


可以和Haskell , Prolog 一样做到模式匹配,

建立逻辑推到规则,描述问题,得出答案。


from pyDatalog import pyDatalog

pyDatalog.create_atoms( 'N, N1, X, Y, X0, X1, X2, X3, X4, X5, X6, X7' )
pyDatalog.create_atoms( 'ok, queens, next_queen, pred, pred2' )

size = 8
ok( X1, N, X2 ) <= ( X1 != X2 ) & ( X1 != X2 + N ) & ( X1 != X2 - N )

pred( N, N1 )   <= ( N > 1 ) & ( N1 == N - 1 )
queens( 1, X )  <= ( X1._in( range( size ) ) ) & ( X1 == X[0] )
queens( N, X )  <= pred( N, N1 ) & queens( N1, X[:-1] ) & next_queen( N, X )

pred2( N, N1 )     <= ( N > 2 ) & ( N1 == N - 1 )
next_queen( 2, X ) <= ( X1._in( range( 8 ) ) ) & ok( X[0], 1, X1 ) & ( X1 == X[1] )
next_queen( N, X ) <= pred2( N, N1 ) & next_queen( N1, X[1:] ) & ok( X[0], N1, X[-1] ) 

print( queens( size, ( X0, X1, X2, X3, X4, X5, X6, X7 ) ) )


python 逻辑推理编程解决八皇后

标签:python   八皇后   

原文地址:http://blog.csdn.net/pandora_madara/article/details/37969173

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!