在线法官中来自 stdin 的 Python 输入

标签 python python-2.7 stdin raw-input

我是竞争性编程和入门的初学者。熟悉C和C++,但是我正在学习Python。我在Python中面临输入困难 问题是这样的:对于给定数量的测试用例,对于每个测试用例,将在同一行中为您提供一个数字 N 和另一个数字 K。在这一行之后,一行中将有 N 个整数。您只需像下面给出的那样进行划分和总结(括号只是为了跟踪)

1 #test cases
3 2 #N  #K
4 5 7 #N integers 

答案是sum : 7,即 4/2 + 5/2 + 7/2 = 7(整数除法)

我编写了一个简单的Python 2.7程序来接受输入并执行操作。

t = map(int,raw_input())
t = t[0]
while t>=0:
    count=0
    n,k = map(int,raw_input().split())
    candies = map(int,raw_input().split())
    for candy in candies:
        count += candy/k
    t -= 1

我收到错误:

vivek@Pavilion-dv6:~/Desktop$ python kids_love_candies.py <in.txt >out.txt 
Traceback (most recent call last):
  File "kids_love_candies.py", line 6, in <module>
    n,k = map(int,raw_input().split())
EOFError: EOF when reading a line

另一个link建议使用 sys.stdin.readline() 读取输入,但我不知道如何将其应用于我的问题。 我应该使用哪一个?为什么?学习和使用它们的正确方法是什么?

最佳答案

您试图读取太多行,您的 while 条件应为 > 0。但这整件事比需要的更复杂

t = int(raw_input()) # no need to map
for _ in range(t): # loop with range instead of manual counting
    # loop body

当我想循环来自 stdin 的行时,我通常使用 sys.stdin 来代替。在这种情况下,您可以忽略计数

raw_input() # ignore the size
for line in sys.stdin:
    n, k = (int(i) for i in line.split())
    count = sum(int(c) for c in raw_input.split()) / k

关于在线法官中来自 stdin 的 Python 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32658996/

相关文章:

python - Pygame Sprite 碰撞检测不起作用

python - MSSQL 的 Scrapy 管道

python - 如何将具有 Etc/GMT 的日期字符串转换为 Python 日期时间?

python - 总结从 'Col' 开始的每列的行值

python - 如何在Python中的函数之间传递变量

python - 高级 Python 正则表达式 : how to evaluate and extract nested lists and numbers from a multiline string?

python - 理解 == 应用于 NumPy 数组

c - 打开()一个文件并在最后写入

python - 将来自 stdin 的整数放入列表中

C++ 使用 istringstream 从 stdin 读取