【发布时间】:2012-11-04 19:36:54
【问题描述】:
我知道这是一个非常基本的问题,但我也是 python 环境的新手。我正在编写我的第一个程序(数据结构问题),我需要阅读一些输入测试用例。
输入:
The first line contains the number of test cases T. T test cases follow.
The first line for each case contains N, the number of elements to be sorted.
The next line contains N integers a[1],a[2]...,a[N].
约束:
1 <= T <= 5
1 <= N <= 100000
1 <= a[i] <= 1000000
示例输入:
2
5
1 1 1 2 2
5
2 1 3 1 2
我编写了一个以下程序来从文件中读取上述输入,但我确信这不是最好的方法,因为它包含很多 if-else 循环和 for 循环,这真的很糟糕大号inputs。
sample = open('sample.txt')
first = sample.readline()
if len(first) > 5 or len(first) <1:
print "Not correct input";
else:
test = sample.readline
for x in range(0,len(first)):
second = sample.readline()
if len(second) >100000 or len(second) < 1:
print "wrong input";
else:
third = list()
for y in range(0, len(third)):
third.append(sample.readline()[:1])
method_test(third) #calling a method for each sample input
请建议我最好的解决方案。
【问题讨论】:
-
你想做什么?看来您的阅读部分已关闭,您是否要限制输入?此外,看起来这两个
ifs 总是会失败(不可能同时满足和条件)。也就是说,他们永远不会打印“输入错误”/“错误输入”。 -
其实我只是想得到一个通用的解决方案来从每个约束的文件中读取示例输入。
-
if len(first) > 5 and len(first) <1没有意义。你的意思可能是or?
标签: python input python-2.7