Python运行时错误在线评测

问题描述:

所以我试图解决从弗吉尼亚在线法官以下问题:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1998Python运行时错误在线评测

我用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?

+0

我在这里看到了一些压痕问题 – Arman

+0

你想分享错误消息? – timgeb

+0

您可能希望将'sys.stdin'与'input()'进行比较。 – AChampion

这比输入使用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 
+0

谢谢!这解决了我的问题 –