[英]python how to read a line until EOF
I am trying to read some lines until EOF for this question:我正在尝试阅读一些行直到 EOF 这个问题:
https://open.kattis.com/problems/tight https://open.kattis.com/problems/tight
Here's what I've tried:这是我尝试过的:
from collections import defaultdict
import sys
def get_ans(n, k):
dp = defaultdict(int)
total = defaultdict(int)
for i in range(n):
for num in range(k+1):
if num+1 <= k:
dp[(i, num)] += dp[(i-1, num+1)]
if num-1 >= 0:
dp[(i, num)] += dp[(i-1, num-1)]
dp[(i, num)] += dp[(i-1, num)]
dp[(i, num)] = max(dp[(i, num)], 1)
total[i] += dp[(i, num)]
return total[n-1]/((k+1)**n)*100
def main():
for line in sys.stdin:
if line == "":
break
print(line)
k, n = map(int, input().split())
ans = get_ans(n, k)
print(str.format('{0:.6f}', ans))
if __name__ == "__main__":
main()
Problem: if I copy the input and paste it all in the terminal to the running script, my output looks like this:问题:如果我复制输入并将其全部粘贴到终端中到正在运行的脚本中,我的输出如下所示:
My input:我的输入:
4 1
2 5
3 5
8 7
Terminal Output终端输出
40.740741
3 5
It seems like the some lines aren't processed -- I don't understand why.似乎有些行没有被处理——我不明白为什么。
Could someone point me in the right direction?有人能指出我正确的方向吗?
In main
I would suggest using a while loop and as already pointed out input
as input
handles incoming data from sys.stdin
for you.在
main
我建议使用 while 循环,并且已经指出input
作为input
处理来自sys.stdin
传入数据。
def main():
line = input()
while line:
k, n = map(int, line.split())
ans = get_ans(n, k)
print(str.format('{0:.6f}', ans))
line = input()
正如@ForceBru 指出的那样,我在input()
而不是line
上进行拆分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.