2013-11-25 35 views
1

的第一個問題:做codeforces問題或TopCoder公司在多個測試用例標準輸入(Python)的有以下形式的輸入今年的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 

通常情況下,你不必輸入5測試用例在彼此之後,你只需要做一個,然後通過20-25個測試案例。

我試圖操縱這些數據使其可用,並想知道如何做到這一點。

例如,如果這只是

5 
2 3 4 5 6 

我可以使用輸入(),以獲得所述第一數目,並且

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,data]這樣的數組,這似乎很難操縱。

如何從標準輸入讀取多個測試用例? (即使一般的答案有幫助,因爲問題本身並不具體)

回答

1

我傾向於把它包裝在一個生成器中。例如:

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 

產生

[email protected]:~/coding$ cat source.txt | python getdata.py 
[['.', '.', '.', 'x'], ['.', '.', 'x', 'x'], ['.', '.', 'x', 'x'], ['.', '.', '.', 'x']] 
[['.', '.', 'x', 'x'], ['.', '.', 'x', 'x']] 
[['x', 'x', '.', '.'], ['x', 'x', '.', '.'], ['.', '.', '.', 'x']] 

這種方式,數據讀取器不關心,如果源是標準輸入,或文件,或什麼的,你可以通過它一些東西,剝去評論如有必要。

相關問題