Chinaunix首页 | 论坛 | 博客
  • 博客访问: 53938
  • 博文数量: 5
  • 博客积分: 2127
  • 博客等级: 上尉
  • 技术积分: 135
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-19 21:20
文章分类

全部博文(5)

文章存档

2011年(5)

分类: Python/Ruby

2011-06-16 15:00:53

    参照文章 用 Haskell 实现的8皇后问题  ,也想写一个Python的实现。
    Python 中引入了不少的函数式编程的东西,几乎就可以从 Haskell 版本直接翻译。由于Python中也有面向过程和面向对象的部分,我们可以充分利用,如传统的循环结构。这样输出部分就好写多了,不过这里我仍然使用了列表解析和zip等极具函数风格的写法。
  1. def safe (poses, pos):
  2.     return not any([pos == p or abs(pos - p)==len(poses) - i for i,p in enumerate(poses)])

  3. def queens(n):
  4.     if n == 0:
  5.         return [[]]
  6.     else:
  7.         return [s+[pos] for s in queens(n-1) for pos in range(1,9) if safe(s, pos)]

  8. result = queens(8)
  9. rows = ['A','B','C','D','E','F','G','H']
  10. print("There are %s solutions in total" %len(result))
  11. for solution in result:
  12.     print ([ col+str(row) for (col, row) in zip(rows, solution)])
运行速度相当快,没必要优化了。结果如下:
There are 92 solutions in total
['A1', 'B5', 'C8', 'D6', 'E3', 'F7', 'G2', 'H4']
['A1', 'B6', 'C8', 'D3', 'E7', 'F4', 'G2', 'H5']
['A1', 'B7', 'C4', 'D6', 'E8', 'F2', 'G5', 'H3']
['A1', 'B7', 'C5', 'D8', 'E2', 'F4', 'G6', 'H3']
['A2', 'B4', 'C6', 'D8', 'E3', 'F1', 'G7', 'H5']
['A2', 'B5', 'C7', 'D1', 'E3', 'F8', 'G6', 'H4']
['A2', 'B5', 'C7', 'D4', 'E1', 'F8', 'G6', 'H3']
……


阅读(3333) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~