1

我想以 Python 的方式尽可能接近地复制以下 C++ 代码,并进行输入和异常处理。我取得了成功,但可能不是我想要的。我本来想退出类似于输入随机字符的 C++ 方式的程序,在这种情况下它是一个“q”。while 条件下的 cin 对象不同于 python 的方式使 while 为真。此外,我想知道将 2 个输入转换为 int 的简单行是否合适。最后,在 python 代码中,“再见!” 由于强制应用程序关闭的 EOF (control+z) 方法,从不运行。有一些怪癖,总的来说,我对 python 所需的代码更少感到满意。

额外:如果您查看最后打印语句中的代码,这是将 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
4

2 回答 2

1

对于该函数hmean,我将尝试执行 return 语句,并在aequals时引发异常-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 转换为 时引发了 a ,您可能需要使用except块。ValueErrorint

于 2013-04-21T23:51:36.937 回答
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 的库,那么您应该不会感到太大的不同。

于 2013-04-22T04:58:41.470 回答