【问题标题】:Why does my Python program give run time error on Kattis interpreter?为什么我的 Python 程序在 Kattis 解释器上出现运行时错误?
【发布时间】:2019-06-26 02:56:19
【问题描述】:

当我将此文件提交给 Kattis 时,我收到了 Run Time Error,没有进一步的解释。看起来很简单的代码,但也许我只是遗漏了一些东西。

它在我的 python 3 解释器上运行。为什么它在 Kattis 上不起作用? (或者可能是其他解释器)

问题:https://open.kattis.com/problems/babelfish

dictionary = dict()
userInput = input()
while userInput != "":
    buf = userInput.split()

    english = buf[0]
    foreign = buf[1]

    dictionary[foreign] = english
    userInput = input()


userInput = input()
while userInput != "":
    if userInput in dictionary:
        print(dictionary.get(userInput))
    else:
        print("eh")

    userInput = input()

【问题讨论】:

  • 您的程序正在无限次地输入。当你得到 EOF 时你应该停下来。

标签: python dictionary


【解决方案1】:

我认为问题在于输入数据没有像您所做的那样使用 input() 函数获得。您应该阅读标准输入,如下所示:

for i in sys.stdin:
    ab = i.split()
    a = int(ab[0])
    b = int(ab[1])
    # Solve the test case and output the answer

Kattis documentation on Python3

【讨论】:

  • 这会不会没有 int 转换?因为不应该有任何整数变量;它是由字典组织的。
  • 哦,是的,我实际上并没有运行您的代码,只是检查了您必须阅读 sys.stdin 变量的文档。可能您只会迭代 i 并将其用作您的值。
  • 这对我也不起作用;在 python3 Linux 编译器上,我使用 input() 函数,它接受标准输入就好了;只有 Kattis 没有。
【解决方案2】:

Kattis 建议使用sys.stdin 来读取输入数据。但是也可以使用input()

第二个 while 循环的中断条件在您的代码中不起作用。 虽然有一个空字符串告诉您第一个块正在结束,但第二个块没有。

在 input() 捕获流中的最后一个数据后,您仍在尝试在下一个循环中使用:userInput = input() 获取更多数据。 因此抛出一个EOFError,你可能会抓住它以获得破坏条件:

while True:
    try:
        userInput = input()
    except EOFError:
        break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2015-08-10
    • 2020-07-16
    相关资源
    最近更新 更多