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

2021-04-01 09:06:26 字數 1810 閱讀 6074

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

count = count + inline_**t

if inline_**t > 0:

print 'find %s %d time(s) in line :%d'%(tag_tok,inline_**t,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 **t;

}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++語言中在開發時的差異了。

python簡單的練習例項

練習幾個簡單的python程式 1 輸出1到100之間所有的偶數 法一 num 1 while true if num 51 break print num 2 num 1 法二 num 2 while num 100 print num num 2 2 輸出1到100的奇數 法一 num 1 wh...

簡單的python爬蟲例項

目標 爬取搜尋出來的所有 中東人 的 先說一下思路 來看爬取的 import requests import re from bs4 import beautifulsoup address url list 用於儲存,每個頁面的url列表 構造url def get url list for i ...

python爬蟲簡單例項

通過在網頁上右鍵來檢視審查元素,然後在html內可以發現以下內容,而爬蟲也正是要爬取這些內容。處理標籤開始 defstart element self,name,attrs if name map name attrs title number attrs href 處理標籤結束 defend el...