gpt4 book ai didi

python - 在 python 中编写代码以从 "txt"文件读取一些示例输入的最佳方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 09:12:44 24 4
gpt4 key购买 nike

我知道这是一个非常基本的问题,但我也是 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 循环,它在处理大型输入 时真的很糟糕。

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

请建议我最好的解决方案。

最佳答案

应该这样做:

with open('sample.txt') as sample:
num_testcases = int(sample.readline())
assert 1 <= num_testcases <= 5
for testcase in range(num_testcases):
num_elems = int(sample.readline())
assert 1 <= num_elems <= 10000
elems = map(int, sample.readline().split())
assert len(elems) == num_elems
assert all(1 <= elem <= 100000 for elem in elems)
method_test(elems)

编辑:添加了有效性检查。

关于python - 在 python 中编写代码以从 "txt"文件读取一些示例输入的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13222114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com