2014-09-27 125 views
1

我最近第一次參加了黑客馬拉松,並陷入了第一個問題。我解決了算法,但無法弄清楚如何使用Python從stdin中獲取值。這是一個問題:使用Python的Stdin問題

有兩個大學生想在宿舍裏聚在一起。宿舍裏有各種大小的房間。有些房間可以容納兩個額外的學生,而另一些則不能。

輸入:第一個輸入行將是一個數字n(1≤n≤100),它是宿舍中的房間總數。之後會有n行,其中每行包含兩個數字,p和q(0≤p≤q≤100)。 P是已經在房間裏的學生人數,而q是可以住在房間裏的最多學生人數。

輸出:打印室,兩個學生可以住在數量

這是我的解決方案。我使用raw_input()測試了它,它在我的解釋器上完美工作,但是當我將其更改爲input()時,我收到一條錯誤消息。

def calcRooms(p, q): 
    availrooms = 0 
    if q - p >= 2: 
     availrooms += 1 
    return availrooms 

def main(): 
    totalrooms = 0 
    input_list = [] 

    n = int(input()) 
    print n 

    while n > 0: 
     inputln = input().split() #accepts 2 numbers from each line separated by whitespace. 
     p = int(inputln[0]) 
     q = int(inputln[1]) 
     totalrooms += calcRooms(p, q) 
     n -= 1 

    return totalrooms 

print main() 

錯誤消息:

SyntaxError: unexpected EOF while parsing 

如何接受正確地從標準輸入數據?

+1

[raw_input](https://docs.python.org/2/library/functions.html#raw_input) – DOOM 2014-09-27 19:06:15

+1

我喜歡使用sys.stdin.readline()或「for sys.stdin中的行:」。然後你可以「line.split()」並轉換爲int或其他。 input()在CPython 2.x中工作,但它是不安全的。在3.x中,我相信input()很好。在2.x中,你必須使用raw_input()並記住不要使用input()。但我仍然喜歡使用sys.stdin。 – user1277476 2014-09-27 19:12:01

回答

3

在這種特殊情況下,使用raw_input將整行作爲字符串輸入。

inputln = raw_input().split()

這需要輸入線作爲字符串和split()方法與空間分割字符串作爲分隔符,並返回一個列表inputln

下面的代碼工作,你想要的方式。

def main(): 
    totalrooms = 0 
    input_list = [] 
    #n = int(input("Enter the number of rooms: ")) 
    n = input() 

    while n > 0: # You can use for i in range(n) : 
     inputln = raw_input().split() #Converts the string into list 

     p = int(inputln[0]) #Access first element of list and convert to int 
     q = int(inputln[1]) #Second element 

     totalrooms += calcRooms(p, q) 
     n -= 1 

    return totalrooms 

或者,您也可以使用fileinput

如果輸入文件未作爲命令行參數傳遞,則stdin將作爲默認輸入流。

import fileinput 
for line in fileinput.input() : 
     #do whatever with line : split() or convert to int etc 

請參考:docs.python.org/library/fileinput.html

希望這會有所幫助,如果需要的話落評論作出澄清。

+0

那麼,raw_input()將與標準輸入一起使用?我必須將我的答案提交給他們將在其中測試代碼的黑客馬拉松網站。沒有人在命令行輸入數字。只是想確定一下,因爲我已經提交了4次wong解決方案,並且開始變得尷尬! – MNRC 2014-09-28 02:51:08

+0

是的,raw_input()將與標準輸入配合使用。通常,黑客馬拉松或在線評判中的測試用例都是具有一系列測試用例的輸入文件。上面的代碼應該可以工作。 – venki421 2014-09-28 06:37:47

+0

我遵循你的解釋,代碼在黑客馬拉松網站上正確提交。非常感謝! – MNRC 2014-09-28 18:09:47