2010-12-06 96 views
0

嘿,這是我在我的cs類中做家庭作業的一個類,現在我正在玩python。我想學習如何在Python中設計類,並希望實現這個。這是一個相對直接的課程。幫助將不勝感激。下面的代碼:在python中實現類

#include <iostream> 
#include <string> 
#include <fstream> 
#include <cstdlib> 
#include <ctime> 
#include <sstream> 
#include <vector> 
#include <cmath> 

using namespace std; 

int num_flights=0 ; 
const int Columns_Total = 14; /*the total columns are 14 for each flight*/ 


class Flight 
{ 
public: 
Flight(); 
void major_calc(string& filename,ifstream& is,string& line, ofstream& os); 
    void print (ofstream& os); 

private: 
vector<vector <double> > store; 
int num_lines; 
double avg_wind_speed; 
double avg_height; 
double avg_tempr; 
double std_dev_speed; 
double std_dev_height; 
double std_dev_tempr; 

    }; 

Flight::Flight() 
{ 

} 

    void Flight::major_calc(string& filename,ifstream& is, string& line, ofstream& os) 
    { num_lines=0; 

vector <double> single_line; /* Vector to one test line of a flight*/ 
vector <double> flight_height; /* Vector stores the heights associated with all the test lines for a particular flight*/ 
vector <double> flight_wind_speed; /* Vector stores the wind speeds associated with all the test lines for a particular flight*/ 
vector <double> flight_tempr; /* Vector stores the temperatures associated with all the test lines for a particular flight*/ 

while(getline(is,line)) 
{ 
if (line.substr(0,3) == "ACM") /* Checks a new flight */ 
{ 
    num_flights++; 
    os << line << endl; 
    return ; 

} 
else 
{ 
    istringstream iss(line,istringstream::in); /* Reading the string*/ 
    double FieldInfo; 
    num_lines++; /* updating the counter*/ 
    for (int n=0; n<14; n++) 
    { 
     iss >> FieldInfo; 
     single_line.push_back(FieldInfo); 
    } 

    store.push_back(single_line); 

    flight_height.push_back(single_line[4]); /* Updates the height vector with the value from a particular test line*/ 
    flight_wind_speed.push_back(single_line[3]); /* Updates the wind speed vector with the value from a particular test line*/ 
    flight_tempr.push_back(single_line[8]);/* Updates the temperature vector with the value from a particular test line*/ 

} 

    single_line.clear(); /* Empties the single line vector so it can be used again*/ 

} 


double temp1=0; /* temporary variables used to calculate the average height, average speed and average temperature*/ 
double temp2=0; 
double temp3=0; 

for (int i=0; i< flight_height.size();i++) 
{ 
    temp1+= flight_height[i]; 
    temp2+= flight_wind_speed[i]; 
    temp3+= flight_tempr[i]; 
} 

avg_height= temp1/(flight_height.size()); 
avg_wind_speed= temp2/(flight_wind_speed.size()); 
    avg_tempr= temp3/(flight_tempr.size()); 


double sqr=2.0; /* Temporary variables used to calculate std deviation associate with the speed, height and the temperature*/ 
double temp4=0; 
double temp5=0; 
double temp6=0; 

for (int i=0; i< flight_height.size();i++) 
{ 
    temp4+= pow((flight_height[i]-avg_height),sqr); 
      temp5+= pow((flight_wind_speed[i]-avg_wind_speed),sqr); 
      temp6+= pow((flight_tempr[i]-avg_tempr),sqr); 
} 

std_dev_height= sqrt(temp4/flight_height.size()); 
std_dev_speed= sqrt(temp5/flight_wind_speed.size()); 
    std_dev_tempr= sqrt(temp6/flight_tempr.size()); 
    } 

    void Flight::print (ofstream& os) 
    { 
os<<"printing the results out"<<endl;   /* Printing out all the values*/ 
os<<"avg speed: "<<avg_wind_speed<<"knots"<<endl; 
os<<"avg height: "<<avg_height<<"feet"<<endl; 
os<<"avg tempr: "<<avg_tempr<<"celcius"<<endl; 
os<<"std dev in height: "<<std_dev_height<<"knots"<<endl; 
os<<"std dev in speed: "<<std_dev_speed<<"feet"<<endl; 
os<<"std dev in temperature: "<< std_dev_tempr<<"celcius"<<endl; 
os<<"The number of lines "<< num_lines<<endl; 

} 


    int main() 
    {   
string filename; 
    string line; 
cout<<"Enter the filename"<<endl; 
cin>>filename; 
ifstream is; 
    is.open(filename.c_str()); /*open the file*/ 
bool FileDoesntExist = is.fail(); 

if(FileDoesntExist) /*checks if the file exists*/ 
{ 
cout << "File doesn't exist" << endl; 
exit(1); 
} 

string fileout = filename.substr(filename.rfind(".")+1,filename.length()) + ".log"; /*making the ouput file */ 
ofstream os (fileout.c_str()); 

vector <Flight> complete; 
while(!is.eof()) 
{ 
    Flight test; 
    while(getline(is,line)) 
    { 
     test.major_calc(filename,is,line,os); 
     test.print(os); 
    } 
    complete.push_back(test); 
} 


return 0; 

}

+5

由於這是一個「相對簡單的類」或許你可以嘗試在Python自己寫的,並當您遇到特定問題時提出問題。我認爲期望有人用Python爲你重寫整個東西有點多。 – 2010-12-06 16:13:04

+0

我從來沒有說過要重寫整個東西......我只是想提示如何改變東西,所以我可以在Python中實現它。對不起,如果你得到了錯誤的信息 – dawnoflife 2010-12-06 16:16:41

回答

1

作爲一個熱心的業餘愛好者,我想我會拿這個一杆了。我重新安排了一些事情;我會很感激任何意見,可以做不同/更好的事情。

import math 
import os 

def avg_dev(arr): 
    """ 
    Calculate mean and standard deviation on an array of values 

    @param arr Array of values 
    """ 
    if len(arr)==0: 
     return 0.0, 0.0 
    else: 
     avg = float(sum(arr))/len(arr) 
     dev = math.sqrt(sum([(i-avg)**2 for i in arr])) 
     return avg,dev 

class Flight: 
    """ 
    Class wraps data about a single flight 
    """ 
    def __init__(self, txt): 
     """ 
     Initialize flight information 

     @param txt List of strings containing per-flight data 
        First row is header, beginning with 'ACM'; 
        remainder are space-delimited columnar data 
     """ 

     self.flightName = txt[0][3:].strip() 
     self.numLines = len(txt)-1 

     height = [] 
     wind = [] 
     temp = [] 
     for ln in txt[1:]: 
      data = ln.split() 
      height.append(float(data[4])) 
      wind.append(float(data[3])) 
      temp.append(float(data[8])) 

     self.avg_height,  self.std_dev_height = avg_dev(height) 
     self.avg_wind_speed, self.std_dev_speed = avg_dev(wind) 
     self.avg_temp,  self.std_dev_temp = avg_dev(temp) 

    def __str__(self): 
     return """Results for %s: 
Speed: avg %f, stddev %f 
Temp: avg %f, stddev %f 
Height: avg %f, stddev %f 

""" % (
      self.flightName, 
      self.avg_wind_speed, self.std_dev_speed, 
      self.avg_temp, self.std_dev_temp, 
      self.avg_height, self.std_dev_height) 


class Flights: 
    """ 
    Container class for multiple flights expressed in a single log file 
    """ 
    def __init__(self, fname): 
     """ 
     Read a flight log file 

     @param fname Name of the log file 
     """ 
     self.filename = fname 
     self.flight = [] 

     inf = file(fname, 'r')   
     txt = [] # per-flight data buffer 
     for ln in inf.readlines(): 
      if ln[:3]=='ACM': # found start of new record 
       if len(txt)>0: # flush buffer 
        self.flight.append(Flight(txt)) 
       txt = [] 
      txt.append(ln) 
     if len(txt)>0:   # clear buffer 
      self.flight.append(Flight(txt)) 
     inf.close() 

    def __iter__(self): 
     return self.flight.__iter__() 

def main(): 
    fname = raw_input("Enter the filename: ") 

    try: 
     # read flight data 
     flight = Flights(fname) 
    except IOError: 
     print "File doesn't exist" 
     sys.exit(1) 

    logname = os.path.splitext(fname)[0] + ".log" 
    logf = file(logname, 'w') 
    for f in flight: 
     logf.write(str(f)) 
    logf.close() 

if __name__=="__main__": 
    main() 

,併爲那些誰想要玩它,僞造的,在測試輸入文件:

ACM The first flight record 
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 
1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1 11.1 12.1 13.1 14.1 
ACM The second flight 
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 
1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1 11.1 12.1 13.1 14.1 
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 
1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1 11.1 12.1 13.1 14.1 
ACM Third flight 
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 
1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1 11.1 12.1 13.1 14.1 
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 
2

有些事情你需要知道,使過渡:

  • 在Python,你做一個類的初始化一種叫做__init__()(而不是Flight(),或者在課堂本身)的方法
  • All insta在Python NCE方法採取self作爲參數
  • 要引用一個實例變量的類從withing類,您使用self.var
  • 在Python,Java不同,C++等,有過類的可見性難以控制屬性,所以你不能申報物品的公共或私人的(雖然你可以給它一個前導下劃線,但是這是一個指引,不是由編譯器執行)

編輯

其他幾個關於如何編寫C++ i的說明n Python:

  • 在Python中不需要像std::vector這樣的東西。我們只使用列表,它可以根據需要進行擴展和縮小,可以包含任何類型的對象,可以被索引和切片,並且可以隨時提供許多有用的方法。
  • 正如我敢肯定你知道,Python是動態類型的,所以你在你的C++做的那些類型聲明的分類 - 過去
0

對於主的事情()我喜歡這個成語:

class Flight(object): 
    # class defined here 

if __name__ == '__main__': 
    # main func defined here 

然後你就可以單元測試/通過在命令行上運行的運行模塊:

python flight.py