不是另一个:LeetCode 中的 EOF 错误消息,在 Visual Studio 中工作正常

Not another one: EOF error message in LeetCode, works fine in Visual Studio

提问人:TheJester_mh 提问时间:12/3/2020 更新时间:12/3/2020 访问量:290

问:

我是 Python3 编码的新手,所以我希望你耐心等待我和我的问题。我在 stackoverflow 和其他网站上发现了类似的问题,但我仍然无法解决问题:

当我在 Visual Studio 中运行以下代码时,一切正常,没有错误消息,什么都没有。 另一方面,在 LeetCode 中,我收到指向第一个输入行的 EOF 错误。

错误消息:EOFError:读取行时的 EOF num = input(“输入一个数字:”) intToRoman 中的第 4 行 (Solution.py) ret = Solution().intToRoman(param_1) 第 56 行 _driver (Solution.py) _driver() 第 67 行 (Solution.py)




代码如下:

class Solution:
num = ""
def intToRoman(self, num: int) -> str:
    num = input("Enter a number: ") 
    while True:
        try:
            num = int(num)
            if num < 0 or num > 3999:  # if not a positive int or inout larger than 3999 print message and ask for input again
                print("Sorry, input must be a positive integer and smaller than 3999, try again")
                continue
            break
        except ValueError:
            return("That's not an int!") # else all is good, number is >=  0 and an integer

Ones = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", ""] # list of single digit roman numbers 
Tens = ["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", ""] # list of double digit roman numbers
Hundreds = ["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", ""] # list of three digit roman numbers
Thousands = ["M", "MM", "MMM", "", "", "", "", "", "", ""] # list of four digit roman numbers
if (len(str((num)))) == 1:
    print (Ones[int(repr(num)[-1]) - 1])
if (len(str((num)))) == 2:
    print (Tens[int(repr(num)[-2]) - 1] + Ones[int(repr(num)[-1]) - 1])
if (len(str((num)))) == 3:
    print (Hundreds[int(repr(num)[-3]) - 1] + Tens[int(repr(num)[-2]) - 1] + Ones[int(repr(num)[-1]) - 1])
if  (len(str((num)))) == 4:
    print (Thousands[int(repr(num)[-4]) - 1] + Hundreds[int(repr(num)[-3]) - 1] + Tens[int(repr(num)[-2]) - 1] + Ones[int(repr(num)[-1]) - 1])

感谢您提供任何类型的反馈,包括在此代码中要优化的内容。

python-3.x eof

评论

0赞 Grismar 12/3/2020
检查文件编码和行尾(Linux LF 与 Windows CR+LF)
0赞 tdelaney 12/3/2020
我还没有尝试解决 LeetCode 中的问题,所以我不确定它应该如何工作。但问题是你正在征求意见,但已被关闭。你应该从stdin获取数据吗?你已经在其他地方读过 stdin 了吗?您可以删除在调用 .要么你没有以这种方式获取数据,要么在你调用此方法之前已经使用了它。sys.stdininput
0赞 J_H 12/3/2020
“while True: convert str to int”是疯狂的。只需转换一次给定的 str 就足够了。
0赞 TheJester_mh 12/3/2020
感谢您到目前为止的所有反馈。
0赞 TheJester_mh 12/3/2020
对不起,评论还没有结束。第 1 行中的类定义“类解决方案”以及第 3 行中的函数参数都给出了。我只是将其余部分复制并粘贴到我的 macOS Visual Studio 中。我会看看行尾@Grismar

答: 暂无答案