1

次の C++ コードを、Pythonic の方法でできるだけ近い入力と例外処理で複製したいと考えています。私は成功を収めましたが、おそらく私が望んでいたものではありませんでした. ランダムな文字を入力するC++の方法と同様に、プログラムを終了したかったのですが、この場合は「q」でした。while 条件の cin オブジェクトは、while を True にする Python の方法とは異なります。また、2 つの入力を int に変換する単純な行が適切な方法であるかどうかも知りたいです。最後に、Python コードでは、「さようなら!」アプリを強制的に閉じる EOF (control+z) メソッドのため、決して実行されません。癖がありますが、Python で必要なコードが少なくなったことに全体的に満足しています。

おまけ: 最後の print ステートメントのコードを見ると、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);
}

パイソン

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
4

2 に答える 2

1

関数については、return ステートメントを実行して、 equalshmeanの場合に例外を発生させようとします。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 を にキャストするときにexcepta が発生する場合は、ブロックを使用することをお勧めします。ValueErrorint

于 2013-04-21T23:51:36.937 に答える