python與c 的對比

2021-04-13 00:39:03 字數 1874 閱讀 8238

一位網友正在學校做課程設計題目,要求在乙個檔案中找到給定單詞出現的位置並統計出現次數。這是乙個比較簡單的文字處理問題, 於是, 我給他用 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

#include

#include

#include

#include

using namespace std;

int brutefind(const char *x, int m, const char *y, int n ,vector& colpos)

}return cnt;}

int count_string(string source, string tag, vector& colpos)

int main()

catch(string file_name)

}while(in_file.eof()==0);

string tag_tok;

vectorcolpos;

colpos.resize(10);

doint count = 0, line_no = 0 , inline_count;

for(line_no = 0 ;line_no < line_count ; line_no++)

cout << " )" << endl;

cout << lines[line_no] << endl;}}

cout << "--------------------------------" <

這個程式用了30分鐘。

從程式長度和程式設計時間上,粗略對比下:

python  5 分鐘 22行

c++       30 分鐘 60多行

從這個簡單的例子中可以大體看到 指令碼語言與c++語言中在開發時的差異了。

文章出自:http://www.chinaasp.com/20051123/python/index.shtml

python語法與C語法對比

python屬於弱型別語言,變數直接使用,不需要定義,所以也沒有型別限制,因為一切python變數都是乙個相當於類的存在 但容易在呼叫變數時寫錯名字,且不易debug出來 有利有弊,c語言強型別,就連定義位置都必須安排的明明白白否則編譯不過哈 python為簡化語言的書寫,減少書寫錯誤概率,有很多語...

Python與C 程式的簡單例項對比

一位正在學校做課程設計題目,要求在乙個檔案中找到給定單詞出現的位置並統計出現次數。這是乙個比較簡單的文字處理問題,於是,我給他用 python 寫了乙個,並打賭在5分鐘內用不到30行程式解決問題。我作到了,下面是程式 if name main file name raw input input th...

C 中 AS與IS 的對比

在c 語言中進行型別轉換的操作符is和as。is和as都是強制型別轉換,但這兩者有什麼相同之處和不同之處呢?在使用is和as需要注意哪些事項?下面我們從簡單的 示例去 這個簡單的問題。注 此博文只是本人學習過程中一些簡要記錄,新手可以看一下,高手略過。is檢查乙個物件是否相容於指定的型別,並返回乙個...