您的位置:首页 > 编程语言 > Python开发

8皇后问题的c++与python实现对比

2008-12-31 09:47 519 查看
    c++经典书多,但貌似不太新,而python则新书很多,能体现一些新思路新概念。看python的书,写python代码,再用c++实现一遍,这样互补的学习方式貌似也蛮适合自己的。
    在《Beginning Python From Novice to Professional》一书的八皇后问题上,python果然精妙而优雅。
   在对待
for each possibility at level 1:
  for each possibility at level 2:
    for each possibility at level n:
    ... 
    is it viable
形式的循环下,它有yield, generator递归。短短20来行代码就搞定了八皇后,如下:
def conflict(state,nextX):
    nextY=len(state)
    if nextY==0:print 0
    for i in range(nextY):
        if abs(nextX-state[i]) in (0,nextY-i):
            return True
    return False

def queen(num,state=()):
    print state
    for pos in range(num):
        if not conflict(state,pos):
            if len(state) == num-1:
                yield (pos,)
            else:
                for result in queen(num,state+(pos,)):
                    yield  (pos,)+result 

def prettyprint(solution):
    def line(pos,length=len(solution)):
        return '. '*pos + 'X' +'. '*(length-pos-1)
    for pos in solution:
        print line(pos)

if __name__=='__main__':
    import random
    prettyprint(random.choice(list(queen(4))))
其中for result in queen(num,state+(pos,)):
                    yield  (pos,)+result 
2句由为精妙,自己苦思很久,没有能完全理解yield的精髓。。。。。

在用c++实现的时候,一直想模仿实现这句话的功能,却被这句话困扰了2个多小时,看书看久了不休息果然效率奇差。
今天早上醒来,才恍然大悟,其实不就是个栈么。
/*
 * =====================================================================================
 *
 *       Filename:  eightqueen.cpp
 *
 *    Description:  8皇后问题,c++实现
 *
 *        Version:  1.0
 *        Created:  2008年12月30日 19时46分52秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li WeiJian (mn), lwj1396@163.com
 *        Company:  hunan university
 *
 * =====================================================================================
 */

#include<vector>
#include<iostream>
#include<cmath>
using namespace std;

bool conflict(const vector<int> &state,int nextX)
{
    int nextY = state.size();
    for(int i=0;i<nextY;i++)
    {
        if(abs(nextX-state[i])==0 || abs(nextX-state[i])==(nextY-i))
            return true;
    }
    return false;
}

void queen(int num,vector<int> &state)
{
    for(int i=0;i<num;i++)
    {
        state.clear();
        state.push_back(i);
        int pos=0;
        while(state.size()!=num)
        {
            if(conflict(state,pos))//冲突了
            {
                if(pos==num-1)//已经是最后一个位置
                {
                    state.pop_back();
                    break;
                }
                pos++;//尝试下一个pos
                continue;
            }
            else//没有冲突
            {
                state.push_back(pos);
                pos=0;
            }
        }
        if(state.size()==num)
            return;
    }
}

void print(int num,const vector<int> result)
{
    for(int i=0;i<result.size();i++)
    {
        for(int j=0;j<result[i];j++)
            cout<<". ";
        cout<<"X ";
        for(int j=0;j<num-result[i]-1;j++)
            cout<<". ";
        cout<<endl;
    }
}

int main()
{
    vector<int> state;
    queen(16,state);
    print(16,state);
}

在实现之后,对比了一下,效率的差距果然满大,python跑14皇后,等了几分钟没搞定,而c++跑16皇后,都是刷的一下出来了,不过可能c++没有用递归也是一个原因。

最后再总结2句:
 1 一本书,无论薄厚,都不能欺负它,不要想1,2天就看完

 2 c++虽然经典,但书籍过老了,要拿一门有活力的语言为它开路,其实boost的c++已经很python了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息