[英]How to read multiple lines input in python
我是Python的新手,我正在嘗試研究Kingdom Connectivity的訪談街問題。 雖然,我設法解決了這個問題,但我無法提供給定格式的輸入,我在我的系統上嘗試了我的解決方案並且輸出是正確的,但是一旦我在那里編譯,就沒有輸出。
輸入格式如下:
5 5
1 2
2 3
3 4
1 3
4 5
請幫我弄清楚如何解決這個問題。
目前,我正在循環中從raw_input()
獲取輸入並使用a.split(' ')
拆分。
以下是問題的一部分:
**Input Description:**
First line contains two integers N and M.
Then follow M lines ,each having two integers say x and y, 1<=x,y<=N , indicating there is a road from city x to city y.
**Output Description:**
Print the number of different paths from city 1 to city N modulo 1,000,000,000(10^9).If there are infinitely many different paths print "INFINITE PATHS"(quotes are for clarity).
**Sample Input:**
5 5
1 2
2 4
2 3
3 4
4 5
**Sample Output:**
2
**Sample Input:**
5 5
1 2
4 2
2 3
3 4
4 5
**Sample Output:**
INFINITE PATHS
這是我的解決方案
import sys
import numpy as np
c=0
x=raw_input()
y=x.split(' ')
l=(int(y[0]),int(y[1]))
e=[raw_input() for i in range(l[1])]
f=[e[i].split(' ') for i in range(l[1])]
a=[map(int,i) for i in f]
b=[[0 for i in a] for j in range(l[0])]
for i in range(l[0]+1):
for j in range(l[0]+1):
if [i,j] in a:
b[i-1][j-1]=1
elif a[i-1][0]>=a[i-1][1]:
print "INFINITE PATHS"
sys.exit(0)
for i in range(0,l[1]):
d=np.linalg.matrix_power(b,i+1)
c+=d[0][l[1]-1]
print c
這是截圖
我發現你的程序很難理解。 所以,我重寫了它,我認為我的版本更容易理解。
import sys
import numpy as np
line = raw_input()
max_val, num_paths = (int(n) for n in line.split())
# a will be a list of tuples of int, taken from the input.
#
# Each tuple represents a path, so this is effectively a sparse representation
# of a square matrix of possible paths.
#
# Input city numbers are 1-based, but we will treat them as 0-based, so
# subtract 1 from each value before appending to array a.
a = []
for _ in xrange(num_paths):
line = raw_input()
# TRICKY: subtract 1 to convert from 1-based to 0-based city numbers
tup = tuple(int(n)-1 for n in line.split())
if len(tup) != 2:
raise ValueError, "input should only have two values per line"
for n in tup:
if not 0 <= n < max_val:
raise ValueError, "value must be in range [1, %d]" % max_val
if tup[0] >= tup[1]:
#raise ValueError, "INFINITE PATHS"
print "INFINITE PATHS"
sys.exit(0)
a.append(tup)
# Expand the sparse matrix representation into an actual square matrix.
# It should have a 1 anywhere a path was indicated with a tuple in list a,
# and a 0 everywhere else.
b = [ [0 for _ in xrange(max_val)] for _ in xrange(max_val)]
for i, j in a:
b[i][j] = 1
c = 0
for i in xrange(num_paths):
d = np.linalg.matrix_power(b, i + 1)
c += d[0][max_val - 1]
print c
給出示例輸入時,我的版本打印2
。
以下是我在研究過程中想到的一些事情:
第一行給出了常量(文檔中的N
和M
,分別表示最大合法值和路徑數)。 您應該將這些值保存在具有良好名稱的變量中,而不是將它們放在列表中並通過列表索引引用它們。 我使用了名稱max_val
和num_paths
。 你自己犯了一個錯誤:你應該找到從城市1到城市N的路徑,所以最后的檢查應該是d[0][max_val - 1]
; 你使用的是l[1]
,它是num_paths
而不是l[0]
。
b
應該是方陣。 您的代碼是根據a
的長度設置寬度,但max_val
和num_paths
可能並不總是相等,因此這是一種危險的方法。
循環遍歷方陣中的每個可能點並檢查它是否應設置為1是很奇怪的。 它的效率也很低,特別是因為in
測試是O(n),其中n是數組a
的長度。 相反,構建空方陣,然后簡單地循環路徑並為每個路徑設置1個值。
同樣,驗證循環中初始化方陣的輸入值是很奇怪的; 最好在輸入循環中讀取輸入值時對其進行驗證。 而且這很危險,因為num_paths
可能與max_val
無關。 這也是效率低下的,因為你在b
每列檢查a[i-1][0]
a[i-1][1]
; 該比較根本不使用值j
。 你每次檢查五次; 每次檢查一次就足夠了。
我使用了一個Python習慣用法,當你不關心那個變量的值時,你可以使用_
(一個下划線)作為變量的名稱。 當我們用循環執行一定次數的事情,並且我們不會使用循環計數器值時,我使用_
作為循環計數器變量。 當然,這不是必不可少的。
回答你的實際問題:我認為你的程序沒有任何可能的方法來產生輸出。 我懷疑運行此測試問題的服務器上可能存在問題。 您的程序應始終打印“INFINITE PATHS”或其他某種整數值。
PS我實際上並不了解你的程序如何運作; 問題描述說你應該提供一些模數為1e9的路徑,我沒有看到任何強制執行的路徑。
您可以按如下方式讀取指定的輸入:
line = raw_input()
n, m = map(int, line.split())
for _ in range(m):
line = raw_input()
x, y = map(int, line.split())
print x, y
如果您在文件input.txt中輸入與腳本相同的文件夾:
with open("input.txt") as f:
l = [int(i) for i in f.readline().split(" ")]
a = []
for line in f.readlines():
a.append([int(i) for i in line.strip().split(" ")])
print(l, a)
如果輸入作為命令行參數傳遞:
import sys
input_string = sys.argv[1]
print(input_string) # test if this prints the input
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.