[英]How to Enter Multi-Input Lines in Ubuntu Terminal Using sys.stdin.readline()
我正在嘗試為 Python 程序輸入兩行輸入。 這個程序的目標是計算一棵樹的高度。 我們得到了一個一開始就有效的程序,我們的工作是讓它更有效率。 然而,在嘗試使代碼更高效之前,我想至少輸入一些輸入以確保我至少直接輸入輸入。
因此,例如,在一行上輸入 5 和輸入 4 -1 4 1 1 會告訴我們有 5 個節點,-1(第一個節點)是根,1 和 1(第 3 和第 4節點)是-1(第一個)節點的子節點,而 4 和 4(第 0 和第 2 個節點)是比方說第 4 個節點的子節點。 然后程序應該輸出 3(這棵樹的高度)。 我在這個程序中遇到的問題(除了我還沒有使它更優化)是讓 python 解釋我所說的輸入的意思。 到目前為止,我已經嘗試過
python3 tree-height.py <<< 5\ 4 -1 4 1 1
例如,但是 self.n 片段吐出一個錯誤(在原始代碼上,所以我可以確保這個輸入在我嘗試編碼之前首先工作),因為它無法稀疏第二位。 有什么想法嗎?
或者,我也嘗試過創建一個文本文件(我們稱之為 test_case),看起來像
5\ 4 -1 4 1 1
並且,作為其他嘗試,也喜歡
5 4 -1 4 1 1
和
5
4 -1 4 1 1
然后嘗試
python3 tree-height.py < test_case
但這也導致了同樣的錯誤。
相關代碼位,並非所有代碼/主要關心讀取部分:
import sys, threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
#Printing to see what is being messed up
print(sys.stdin.readline())
class TreeHeight:
def read(self):
self.n = int(sys.stdin.readline())
self.parent = list(map(int, sys.stdin.readline().split()))
#Printing to see what is being messed up
print("Self.n is ",self.n)
print("self.parent is ",self.parent)
def compute_height(self):
# Replace this code with a faster implementation
# Removed this bit to protect the author? It works, but I don't want to
get in trouble
def main():
tree = TreeHeight()
tree.read()
print(tree.compute_height())
threading.Thread(target=main).start()
另外:請不要回復說 sys.stdin.readline() 已過時/使用 input(); 我也更喜歡這種方法,但我想(1)學習前者,(2)我在學習在線課程時正在學習這個,我想堅持它將使用的自動測試儀。
編輯:我也嘗試過使用 \ 和 \n (以及變體)(事實上,我真的不記得我嘗試過的所有內容),但我不斷收到此錯誤消息:
ValueError: invalid literal for int() with base 10: '4 -1 4 1 1'
后跟空格的反斜杠不是換行符。
最簡單的方法是使用 here-doc:
python3 tree-height.py <<EOF
5
4 -1 4 1 1
EOF
如果要使用此處的字符串,則需要在其中添加換行符。 您可以使用$'...'
來允許您輸入帶有轉義序列的字符串。
python3 tree-height.py <<< $'5\n4 -1 4 1 1'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.