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

时间:2016-02-28 20:10:23

标签: python runtime-error

所以我试图从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?

1 个答案:

答案 0 :(得分:0)

使用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