在线判断中的 Python 运行时错误



所以我试图从UVa在线判断解决以下问题:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1998

我用Python编写了以下代码:

while True:
    try:
        aux = [0, 0]
        books = int(input())
        prices = [int(x) for x in input().split()]
        money = int(input())
        prices.sort()
        for i in range(0, len(prices)-1, 1):
            for j in range(len(prices)-1, 0, -1):
                if(j == i):
                    break
                if(prices[i] + prices[j] == money):
                    aux[0] = prices[i]
                    aux[1] = prices[j]
print("Peter should buy books whose prices are %d and %d. n" %   (aux[0], aux[1]))

except EOFError:
    break

我认为这可能与给出输入的方式有关;如果每个测试用例都用空行分隔,我如何忽略这一行并继续读取输入直到 EOF?

使用sys.stdin比使用输入更容易。使用生成器使错误处理变得容易,因为for将在到达EOF时终止(next()抛出StopIteration):

import sys
from itertools import combinations
def load():
    while True:
        books = int(next(sys.stdin))
        prices = sorted(int(x) for x in next(sys.stdin).split())
        money = int(next(sys.stdin))
        yield books, prices, money
        next(sys.stdin)  # Skip blank line
for b, ps, m in load():
    i, j = max(((i,j) for i, j in combinations(ps, 2) if i+j == m), key=lambda x: x[0])
    print("Peter should buy books whose prices are {} and {}".format(i, j))
    print('')

输出:

Peter should buy books whose prices are 40 and 40
Peter should buy books whose prices are 4 and 6

最新更新