Python Online Judge 运行时错误
Python Runtime error in Online Judge
所以我想解决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
所以我想解决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