使用Python的Stdin问题

2024-05-13 20:51:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近第一次参加了hackathon,第一个问题就解决了。我解决了这个算法,但不知道如何使用Python从stdin获取值。问题是:

有两个大学生想合租一间宿舍。宿舍里有各种大小的房间。一些房间可以容纳两个额外的学生,而其他房间则不能。

输入:第一行输入n(1 ≤ n ≤ 100),即宿舍的总房间数。之后将有n行,其中每行包含两个数字p和q(0 ≤ p ≤ q ≤ 100)。P是已经在房间里的学生人数,而q是可以住在房间里的最大学生人数。

输出:打印两个学生可以居住的房间数。

这是我的解决方案。我已经用raw\u input()测试了它,它在我的解释器上运行得非常好,但是当我将它改为just 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

如何正确地接受来自stdin的数据?你知道吗


Tags: 消息inputdef错误stdin学生int房间
1条回答
网友
1楼 · 发布于 2024-05-13 20:51:12

在这种特殊情况下,使用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

希望这能有所帮助,如有需要,请发表评论澄清。你知道吗

相关问题 更多 >