转载:Python 与 C++ 程序的简单实例对比

来源:互联网 发布:windows 3d图形编程 编辑:程序博客网 时间:2024/03/29 10:17

albertlee的专栏

  CSDN |  社区 |  技术中心 |  BLOG首页 |  我的首页 |  个人档案 |  联系作者 |  聚合  |   |  搜索 |  登录
  9篇原创: 0篇翻译: 0篇转载: 4485次点击: 24个评论: 0个Trackbacks

文章

  • 职业人文(RSS)

收藏

相册

  • My pic

ASM/C/C++

  • 中国程序网
  • 猎头 2
  • 猎头生活 给我的启示

Linux

Python

Windows

人文人生

  • 你不能没有激情与勇气——可口可乐总裁告诫
  • 猎头3

存档

  • 2004年11月(1)
  • 2004年09月(4)
  • 2004年08月(2)
  • 2004年07月(1)
  • 2004年06月(1)

最近评论

  • Smileonce:有意思,尤其是第一个。说明Python的重定义流的能力不在C++之下。
  • fidys:Vc7.0 Win32 Console 程序
    // Find.cpp : 定义控制台应用程序的入口点。
    //
    #include "stdafx.h"
    #include <fstream>
    #include <iostream>
    #include <vector>
    #include ……
  • 计算机界的律师:我也在做课程设计,但是学校要求用类对象,文件及类库实现随机化.
    高手指教啊??

    #include<iostream.h>
    #include<stdlib.h>
    int rolldice(void);
    main()
    {
    int sum,m,n,he,i,score,x;
    unsigned see……
  • 计算机界的律师:我这有一个小程序,我打算用文件和类对象实现,如何做啊??

    #include<iostream.h>
    #include<stdlib.h>
    int rolldice(void);
    main()
    {
    int sum,m,n,he,i,score,x;
    unsigned seed;
    cout<……
  • 计算机界的律师:你们的语言学的还可以啊???

    不错啊


作者tag:c/c++ CSDN 推荐tag:c++ tag python vector source 
<<等待1095 | 

 Python 与 C++ 程序的简单实例对比

        一位网友正在学校做课程设计题目,要求在一个文件中找到给定单词出现的位置并统计出现次数。这是一个比较简单的文本处理问题, 于是, 我给他用 python 写了一个,并打赌在5分钟内用不到30行程序解决问题。 我作到了,下面是程序:

if __name__=='__main__':
    file_name = raw_input('Input the file you want to find in:')
    try:
        in_file = open(file_name,'r')
        lines = in_file.readlines()


        tag_tok = ''
        while tag_tok.upper() != 'Q':
            tag_tok = raw_input('Input the word you want to find(Q for quit):')
            if tag_tok.upper() != 'Q':
                count = 0
                line_no = 0
                for line in lines:
                    line_no = line_no + 1
                    inline_cnt = line.count(tag_tok)
                    count = count + inline_cnt
                    if inline_cnt > 0:
                        print 'Find %s %d time(s) in line :%d'%(tag_tok,inline_cnt,line_no)
                        print line
                print '---------------------------------'
                print 'Total fount %s %d time(s)'%(tag_tok, count)
    except:
        print "Can't open file %s"%(file_name)

但是,这个网友还不满足非要一个 C++的程序,理由是他们老师不会python , 正好我也想试试用C++解决和python做下对比:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int BruteFind(const char *x, int m, const char *y, int n ,vector<int>& colpos) {
  int i, j, cnt=0;
  /* Searching */
  for (j = 0; j <= n - m; ++j) {
   for (i = 0; i < m && x
== y[i + j]; ++i);
    if (i >= m){
     colpos[cnt++] = j;
     if(cnt == colpos.size())
      colpos.resize(cnt * 2);
    }
  }
  return cnt;
}

int count_string(string source, string tag, vector<int>& colpos){
  int find_cnt = 0;
  find_cnt = BruteFind(tag.c_str(), tag.size(), source.c_str(),source.size(),colpos);

  return find_cnt;
}

int main(){
string file_name, line;
vector<string> lines;
  lines.resize(10);
  
cout << "Input the file name:";
cin  >> file_name;

ifstream in_file;
try{
     in_file.open(file_name.c_str());
     if(!in_file)
       throw(file_name);
  }
  catch(string file_name){
     cout << "Fatal error: File not found."<<endl;
     exit(1);
  }

int line_count = 0;

do{
    getline(in_file, lines[line_count]);
    line_count ++;
    
    if(line_count == lines.size()){
     lines.resize(line_count * 2);
    }
  }while(in_file.eof()==0);

string tag_tok;
vector<int> colpos;
colpos.resize(10);

do{
  cout << "Input the word you want to find(Q for quit):";
  cin >> tag_tok;
  if(tag_tok == "Q"){
   break;
  }
  
  int count = 0, line_no = 0 , inline_count;
  for(line_no = 0 ;line_no < line_count ; line_no++){
   inline_count = count_string(lines[line_no], tag_tok, colpos);
   count += inline_count;
   if(inline_count > 0){
    cout << "Find " << tag_tok << " " << inline_count << " time(s) in line " << line_no ;
    cout << " , column pos is ( ";
    
    for(int i = 0 ;i< inline_count ;i++){
     cout << colpos
<< ' ';
    }
    cout << " )" << endl;
    cout << lines[line_no] << endl;
   }
  }
  cout << "--------------------------------" <<endl;
  cout << "Total fount " << tag_tok << " " << count << " time(s)" << endl;
}while(tag_tok != "Q");

in_file.close();
return 0;
}

这个程序用了30分钟。

从程序长度和编程时间上,粗略对比下:

Python  5 分钟 22行

C++       30 分钟 60多行

从这个简单的例子中可以大体看到 脚本语言与C++语言中在开发时的差异了。



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=27682


[收藏到我的网摘]  albertlee发表于2004年06月27日 11:52:00

相关文章:
  • python起步 2006-06-05 ChinaGnu
  • zoj1061 Web Navigation 2006-07-10 fairylan
  • 对输出“菱形”图案程序的讨论与优化 2006-05-16 dragonxie1983
  • [C++]C++中的時間 2004-09-21 bgu
  • 《C++捷径教程》读书笔记--Chapter 3--基本数据类型 2005-11-07 Micro_lee



特别推荐:
  • gameloft招聘php程序员
    Gameloft成立于1999年的法国,同年成为该 Gameloft公司是世界领先的手机、游戏软件开发 ai
  • 下围棋什么时候电脑能战胜人脑
    中国围棋国手 大学教授告诉你 ai
  • 北大青鸟(西安兆隆)聘.net培训师
    在校生近两千人,在职员工100余名,规模上已发展成 西安最大的软件工程师网络工程师培训基地之一 ai
  • 青娱乐招聘高级运维工程师
    “青娱乐”Qyule.com是国内领先的网络视频网 ai
  • 主机完全DIY,域名免费试用
    时代互联100M主机 216元/年 ai
<<等待1095 | 

#  周星星 发表于2004-06-27 13:03:00  IP: 219.145.130.*
:)Python是一个很好的动态语言,个人认为它可以成为C++最好的帮手。但对于同一个算法而言Python不可能比C++快,这是由运行机制决定的。
我也想用C++实现一下试试看,但实在看不懂题目要求:
a. "给定单词出现的位置" 是不是所有出现的位置,位置以什么来表示,是单词在文件中的偏移吗?
b. 对于文本"aaa",这其中算有个几个"aa",是算一个,还是算两个,如果是算一个,是算前一个,还是算后一个?
而看您写的C++代码,说实话,变量太多,而且变量的作用域都非常的大,一时半会我也看不懂。
想通过运行您写的C++代码来反推出题目要求,可以在VC6.0中又编译不通过,遗憾。

#  whatever 发表于2004-06-27 13:56:00  IP: 155.97.192.*
你的例子证明了:不同语言有各自的适用范围--不过,这个话谁都懂,似乎不用证明。:)

#  albertlee 发表于2004-06-28 10:57:00  IP: 218.69.101.*
程序是在网吧写的. 那个C++程序是在 Borland C++ 5.5下编译过的.

#  周星星 发表于2004-06-30 15:37:00  IP: 219.145.130.*
看你写的python代码明白了你的意图
你用了python中的count函数,而你在C++没有利用已有的类似函数,而是自己写算法,这当然没法比啦
C++的count函数统计的元素,而search函数才是查找子序列。

#  乾坤一笑 发表于2004-06-30 18:00:00  IP: 218.79.105.*
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;

int main(int argc, char *argv[])
{
string strFile, strTarget, strBuf;
vector<string> lines;

// get Data from file & console
cout<< "Input file Name : "; cin >> strFile; ifstream inFile(strFile.c_str());
if (!inFile) { cerr<< "Error when open file! halt!"; return -1; }
cout << "Input the word you want to find(Q for quit):";
cin >> strTarget; if (strTarget == "Q" || strTarget =="q" ) return 0;
do { getline( inFile, strBuf ); lines.push_back(strBuf);
} while (inFile.eof()==0);

// deal with data
int countInLine = 0, countTotal = 0, lineNo = 0;
for (vector<string>::iterator iter=lines.begin(); iter<lines.end(); iter++ ) {
string::size_type pos = 0; int prePos = 0; string strTmp;
while ( (pos = (*iter).find_first_of(' ',pos)) != string::npos) { // slipt words
strTmp = (*iter).substr(prePos, pos-prePos);
if (strTmp==strTarget) countInLine++; prePos = 1 + pos++; }
strTmp = (*iter).substr(prePos, pos-prePos); // deal with the last word
if (strTmp==

#  albertlee 发表于2004-07-01 18:12:00  IP: 211.97.50.*
多谢星星哥

#  周星星 发表于2004-07-01 11:23:00  IP: 219.145.130.*
为了突出算法,我将条件输入去掉了

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>
using namespace std;

struct SmileOnce
{
void operator()( const string& line )
{
cout << "LINE" << ++linenum << ' ';
for( char const* p=line.begin(); (p=search(p,line.end(),str.begin(),str.end()))!=line.end(); p+=str.length() )
{
cout << ',' << (p-line.begin()+1);
++num;
}
cout << endl;
}
SmileOnce( const string& s,size_t& n ) : str(s),linenum(0),num(n) {}
private:
const string& str;
size_t linenum;
size_t& num;
};

int main( int argc, char *argv[] )
{
// 已知条件
string filename = "D://test.txt";
string str = "abc";
// 开始处理
size_t num = 0;
for_each( istream_iterator<string>(ifstream(filename.c_str())),istream_iterator<string>(),SmileOnce(str,num) );
cout << "共找到" << num << "处." << endl;
return 0;
}

#  周星星 发表于2004-07-03 15:14:00  IP: 219.140.161.*
原 来所犯错误:istream_iterator<linestring>(file)迭代的是字符串,而不是文件中的行,需要自己写一个 linestring和对应的istream& operator >>( istream& in, linestring& rch )

经VC++6.0和DevC++4948编译运行测试通过

class linestring : public string{};
inline istream& operator >>( istream& in, linestring& rch )
{
return getline( in, rch );
}

struct SmileOnce
{
void operator()( const string& line )
{
++linenum;
string::const_iterator p = search(line.begin(),line.end(),str.begin(),str.end());
if( p!=line.end() )
{
cout << "LINE" << linenum << ": " << (p-line.begin()+1);
++num;
p+=str.length();
for( ;(p=search(p,line.end(),str.begin(),str.end()))!=line.end(); p+=str.length() )
{
cout << ',' << (p-line.begin()+1);
++num;
}
cout << endl;
}
}
SmileOnce( const string& s,size_t& n ) : str(s),linenum(0),num(n) {}
private:
const string& str;
size_t linenum;
size_t& num;
};

int main( int argc, char *argv[] )
{
// 已知条件
string filename = "D://test.txt";
string str = "abc";
// 开始处理
size_t num = 0;
ifstream file( filename.c_

#  albertlee 发表于2004-07-05 10:58:00  IP: 211.97.50.*
学习先,看来我对C++的了解实在太浅薄了。

不过我也使接触C++好长时间的人了,虽然没学好,但是这是不是从反面说明了Python的简单易学呢?

#  glacjay 发表于2004-12-24 20:25:00  IP: 218.94.9.*
应该可以各取所长吧,好像是用C++写具体的类,然后用PYTHON调用,忘了从哪里看的.

#  计算机界的律师 发表于2004-12-28 09:49:00  IP: 221.212.232.*
你们的语言学的还可以啊???

不错啊

#  计算机界的律师 发表于2004-12-28 09:51:00  IP: 221.212.232.*
我这有一个小程序,我打算用文件和类对象实现,如何做啊??

#include<iostream.h>
#include<stdlib.h>
int rolldice(void);
main()
{
int sum,m,n,he,i,score,x;
unsigned seed;
cout<<"请输入一个随机的数字:";
cin>>seed;//输入随机数种子
srand(seed);//将种子传给RAND

for(n=1;n<=20;n++)
{
sum=rolldice();//第一轮计算和数
cin>>he;
if(he==sum)
{cout<<"cougratulation,please do another question"<<endl;
n=n+1;
x=10;
}
else
{cout<<"请再输入一次:"<<endl;
cin>>he;
if(he==sum)
{cout<<"很好,你是对的:"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你还有最后依次机会,请你输入答案:"<<endl;
cin>>he;
if(he==sum)
{cout<<"是的,你是对的!"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你没有机会了"<<endl;
n=n+1;
x=0;
cout<<"正确的答案是:"<<sum<<endl;
}
}
}
} }//对和的值进行判断
int rolldice(void)
{int die1,die2,worksum,i,he;
char t;
for(i=1;i<=20;i++)
{
worksum=die1+die2;
die1=1+rand()%9;
die2=10-rand()%20;
worksum=die1+die2;//出题,输入结果,给出答案
if(die2>0)
t='+';
else
t='-';
cout<<"请运算"<<die1<<t<<die2<<'='<<endl;//列出公式
cout<<"请作答:"<<endl;
return worksum;
}
}

#  计算机界的律师 发表于2004-12-28 09:55:00  IP: 221.212.175.*
我也在做课程设计,但是学校要求用类对象,文件及类库实现随机化.
高手指教啊??

#include<iostream.h>
#include<stdlib.h>
int rolldice(void);
main()
{
int sum,m,n,he,i,score,x;
unsigned seed;
cout<<"请输入一个随机的数字:";
cin>>seed;//输入随机数种子
srand(seed);//将种子传给RAND

for(n=1;n<=20;n++)
{
sum=rolldice();//第一轮计算和数
cin>>he;
if(he==sum)
{cout<<"cougratulation,please do another question"<<endl;
n=n+1;
x=10;
}
else
{cout<<"请再输入一次:"<<endl;
cin>>he;
if(he==sum)
{cout<<"很好,你是对的:"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你还有最后依次机会,请你输入答案:"<<endl;
cin>>he;
if(he==sum)
{cout<<"是的,你是对的!"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你没有机会了"<<endl;
n=n+1;
x=0;
cout<<"正确的答案是:"<<sum<<endl;
}
}
}
} }//对和的值进行判断
int rolldice(void)
{int die1,die2,worksum,i,he;
char t;
for(i=1;i<=20;i++)
{
worksum=die1+die2;
die1=1+rand()%9;
die2=10-rand()%20;
worksum=die1+die2;//出题,输入结果,给出答案
if(die2>0)
t='+';
else
t='-';
cout<<"请运算"<<die1<<t<<die2<<'='<<endl;//列出公式
cout<<"请作答:"<<endl;
return worksum;
}
}

#  fidys 发表于2005-04-03 19:24:00  IP: 202.117.212.*
Vc7.0 Win32 Console 程序
// Find.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;

typedef istream_iterator<string> In_str;
In_str end;

//统计类
class Count
{
public:
Count(string const & f) :ob(f),line(0),count(0){}
void operator()(char const * second)
{
istringstream is(second);
In_str begin(is);
++line;
for(int x=1;begin!=end;++x,++begin)
{
if(ob==(*begin)) {++count;place.push_back(make_pair(x,line));}
}
}
void out()
{
cout<<"/n你想找的字符出现了"<<count<<"次。/n";
if(count)
{
cout<<"分别出现在以下位置:/n";
for(int i=0;i<count;i++)
{
cout<<"第"<<i+1<<"次在 第"<<place[i].second<<"行,第"<<place[i].first<<"个单词的位置出现/n";
}
}
}
private:
vector<pair<int,int> > place;
long count;
string ob;
long line;
};

//主程序
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"请输入文件名:";
std::ifstream fp((*In_str(cin)).c_str());
if(fp)
{
cout<<"/n输入你想找的字符:";
Count cn(*In_str(cin));

发表评论

  大名: 网址: 评论 
   
 
原创粉丝点击