今年的facebook黑客杯的第一个问题有以下形式的输入:
3 #number of test cases
4 #number of rows of test case 1
. . . x
. . x x
. . x x
. . . x
2 #number of rows of test case 2
. . x x
. . x x
3 #number of rows of test case 3
x x . .
x x . .
. . . x通常,在执行代码强制问题或topcoder时,您不必彼此输入5个测试用例,只需为一个测试用例输入,然后由它们运行20-25个测试用例。
我费了很大的劲才想要操纵这些数据以使其可用,我想知道如何才能做到这一点。
例如,如果它只是
5
2 3 4 5 6我可以使用the ()获得第一个数字,并且
import sys
data = []
for line in sys.stdin:
y = [int(x) for x in line.split()]
data.append(y)来操纵剩下的。如果我为这个问题做了类似的事情(用str代替int ),我最终会得到一个数组,比如3,4,data,2,data,3,这些数据似乎很难操作。
如何从stdin读取多个测试用例?(即使是一般的答案也有帮助,因为问题本身并没有那么具体)
发布于 2013-11-25 03:51:00
我倾向于用发电机把这个包起来。例如:
import sys
def read_data(source):
N = int(next(source))
for case in range(N):
num_rows = int(next(source))
rows = [next(source).split() for i in range(num_rows)]
yield rows
for case in read_data(sys.stdin):
print case产生
dsm@notebook:~/coding$ cat source.txt | python getdata.py
[['.', '.', '.', 'x'], ['.', '.', 'x', 'x'], ['.', '.', 'x', 'x'], ['.', '.', '.', 'x']]
[['.', '.', 'x', 'x'], ['.', '.', 'x', 'x']]
[['x', 'x', '.', '.'], ['x', 'x', '.', '.'], ['.', '.', '.', 'x']]这样,数据读取器就不关心源是stdin,还是文件,或者其他什么,您可以传递一些必要时删除注释的内容。
https://stackoverflow.com/questions/20184382
复制相似问题