欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python 示例分享---逻辑推理编程解决八皇后

程序员文章站 2024-01-27 08:19:40
可以和haskell , prolog 一样做到模式匹配, 建立逻辑推到规则,描述问题,得出答案。 from pydatalog import pydatalo...

可以和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 ) ) )