为什么我的Python代码无法接受输入?

问题描述 投票:8回答:3

我为SPOJ.com中的“时尚”问题编写的代码无法正确接收以下输入:

2
2
1 1
3 2
3
2 3 2
1 3 2

代码:

x = int(input())
spam = []

for i in range(x):
    y = int(input())
    for j in range(y):
        z = list(map(int, input().split()))
        if j == 0:
            z.insert(0,y)
        spam.extend(z)

目的是将所有输入(除第一个数字外)存储在垃圾邮件列表中,然后将其用于解决问题。有人可以推荐此修复程序吗?

python python-3.x eof
3个回答
3
投票

我一直在研究Fashion问题,这是您可以接受输入并成功提交问题的方式:

t = int(input()) # number of  test cases 
# from the problem
# Each test case consists of 3 lines:

# The first line contains a single integer N (1 <= N <= 1000).
# The second line contains N integers separated by single spaces denoting the hotness levels of the men.
# The third line contains N integers separated by single spaces denoting the hotness levels of the women.

for _ in range(t):
    int(input()) # first line contian the number of participants, we do not need
    men_data = sorted(map(int, input().split()))
    women_data = sorted(map(int, input().split()))

    print(sum(m*w for m, w in zip(men_data, women_data)))

因此,在您的情况下,y被错误地认为是下一行的号码,y是给您下两行的号码,换句话说,是参与者的数量


1
投票

鉴于spam将是一个平面列表,实际上您不需要所有这些嵌套循环。一个列表理解就足够了。

from itertools import islice

spam = [int(x) for line in islice(sys.stdin, 1, None) for x in line.split()]

尽管请注意,这确实假定应该使用标准输入的all。例如,如果您只想读取重定向文件的开头,或者从终端以交互方式输入数据,则这是不合适的,因为我们没有使用行数来控制循环何时停止。


0
投票

此代码有效。输入if后,您应该获得y条件。

x = int(input())    

spam = []
for i in range(x):
    y = int(input())
    if y == 0:
        z.insert(0,y)
        pass
    for j in range(y):
        z = list(map(int, input().split()))   
        spam.extend(z)

print(spam)
© www.soinside.com 2019 - 2024. All rights reserved.