2013-04-21 57 views
1

我想用pythonic的方式儘可能接近地複製下面的C++代碼,並且輸入和異常處理儘可能地接近。我取得了成功,但可能不是我想要的。我希望退出類似於C++輸入隨機字符的程序,在這種情況下它是'q'。 while條件中的cin對象與python創建while時的方式不同。另外我想知道將2個輸入轉換爲int的簡單行是否是一種適當的方式。最後,在Python代碼中,「再見!」從未運行,因爲強制應用程序關閉的EOF(控制+ z)方法。有怪癖,總體而言,我對python中所需的代碼越少感到滿意。Python輸入和異常與C++

額外:如果您查看最後一次打印語句中的代碼,是將var和字符串一起打印的好方法嗎?

任何簡單的技巧/技巧都是受歡迎的。

C++

#include <iostream> 

using namespace std; 

double hmean(double a, double b); //the harmonic mean of 2 numbers is defined as the invese of the average of the inverses. 

int main() 
{ 
    double x, y, z; 
    cout << "Enter two numbers: "; 

    while (cin >> x >> y) 
    { 
     try  //start of try block 
     { 
      z = hmean(x, y); 
     }   //end of try block 
     catch (const char * s)  //start of exception handler; char * s means that this handler matches a thrown exception that is a string 
     { 
      cout << s << endl; 
      cout << "Enter a new pair of numbers: "; 
      continue;  //skips the next statements in this while loop and asks for input again; jumps back to beginning again 
     }          //end of handler 
     cout << "Harmonic mean of " << x << " and " << y 
      << " is " << z << endl; 
     cout << "Enter next set of numbers <q to quit>: "; 
    } 
    cout << "Bye!\n"; 

    system("PAUSE"); 
    return 0; 
} 

double hmean(double a, double b) 
{ 
    if (a == -b) 
     throw "bad hmean() arguments: a = -b not allowed"; 
    return 2.0 * a * b/(a + b); 
} 

的Python

class MyError(Exception): #custom exception class 
    pass 

def hmean(a, b): 
    if (a == -b): 
     raise MyError("bad hmean() arguments: a = -b not allowed") #raise similar to throw in C++? 
    return 2 * a * b/(a + b); 

print "Enter two numbers: " 

while True: 
    try: 
     x, y = raw_input('> ').split() #enter a space between the 2 numbers; this is what .split() allows. 
     x, y = int(x), int(y) #convert string to int 
     z = hmean(x, y) 
    except MyError as error: 
     print error 
     print "Enter a new pair of numbers: " 
     continue 

    print "Harmonic mean of", x, 'and', y, 'is', z, #is this the most pythonic way using commas? 
    print "Enter next set of numbers <control + z to quit>: " #force EOF 

#print "Bye!" #not getting this far because of EOF 

回答

1

對於功能hmean我會試圖執行return語句,並引發異常,如果a等於-b

def hmean(a, b): 
    try: 
     return 2 * a * b/(a + b) 
    except ZeroDivisionError: 
     raise MyError, "bad hmean() arguments: a = -b not allowed" 

要在字符串變量插值的方法format是一種常見的替代:

print "Harmonic mean of {} and {} is {}".format(x, y, z) 

最後,你可能想,如果鑄造X或Y時int一個ValueError被提升到使用except塊。

+0

在C++中「提高」等價於「throw」嗎?感謝您的替代方法。指出。 – 2013-04-22 00:18:49

+1

@klandshome是的,我也建議您查看['signal'模塊](http://docs.python.org/2/library/signal.html)來處理按鍵事件。 – 2013-04-22 01:04:00

+0

異步事件。我會閱讀有關的。 – 2013-04-22 01:07:33

1

這是我想要拋棄的一段代碼。類似的東西是不是在C++容易實現,但它通過分離關注使事情在Python更清晰:

# so-called "generator" function 
def read_two_numbers(): 
    """parse lines of user input into pairs of two numbers""" 
    try: 
     l = raw_input() 
     x, y = l.split() 
     yield float(x), float(y) 
    except Exception: 
     pass 

for x, y in read_two_numbers(): 
    print('input = {}, {}'.format(x, y)) 
print('done.') 

它採用所謂的發電機的功能,只有處理輸入解析到輸入從計算分開。這並不是「儘可能接近」,而是你所要求的「pythonic方式」,但我希望你會發現這個有用。另外,我冒昧地使用浮點數來代替數字。

還有一件事:升級到Python 3,版本2不再開發,只是接收錯誤修正。如果你不依賴任何僅適用於Python 2的庫,你應該不會感覺太大。

+0

這是深入的。感謝您的努力,因爲我會研究您的代碼。我現在有點傾向於使用python 2.7,因爲它對Django框架有最好的支持。糾正我,如果我錯了。 – 2013-04-22 06:52:57

+0

注意到使用浮標。 – 2013-04-22 06:54:03