【发布时间】:2020-12-25 04:19:46
【问题描述】:
编写了一个从文件 input.txt 读取的 python 脚本
输入.txt
2 //number of test cases
2 4 //testcase 1 ->'2' is size of 1st array and 4 is size of 2nd array
6 10 6 7 8 9 //testcase 1 -> 1st array is [6,10] and 2nd array is [6,7,8,9]
1 3 //testcase 2 ->'1' is size of 1st array and 3 is size of 2nd array
7 7 8 14 //testcase 2 -> 1st array is [7] and 2nd array is [7,8,14]
文件中的第一行表示测试用例的数量。在这个例子中,我们有 2 个测试用例。 每个测试用例有 2 行要处理 - 其中第一行表示第一个数组的大小和第二个数组的大小。第二行表示两个数组的详细信息。
即,在上面的示例中,第 2 行表示 testcase1 的第一个数组和第二个数组的大小。第 3 行表示 testcase1 中提到的大小的 2 个数组。第 4 行表示 testcase2 的第一个数组和第二个数组的大小。第 5 行表示 testcase2 中提到的大小的 2 个数组。
我需要检查每个测试用例的第一个数组的元素是否存在于第二个数组中。我写了下面的程序,但这只会执行 1 个测试用例(即,我通过检查 i == 0 手动检查第 2 行和第 3 行)
from itertools import islice
def search(arr, element):
for i in range(len(arr)):
if int(arr[i]) == int(element):
return "yes"
return "no"
f = open("output.txt", "w")
with open("input.txt") as y_file:
count = y_file.readline()
if(count > 0):
for i, line in enumerate(y_file):
if(i == 0):
num, size = line.split()
split_list = [int(num), int(size)]
if(i == 1):
temp = iter(line.split())
res = [list(islice(temp, 0, ele)) for ele in split_list]
for i in range(len(res[0])):
result = search(res[1], res[0][i])
f.write("The result is : " + str(result) + "\n")
f.close()
谁能帮帮我?
输出会是这样的
The result is : yes
The result is : no
The result is : yes
【问题讨论】:
-
你知道 abt any() 函数吗?
-
这有助于搜索吧?程序仅适用于 1 个测试用例。即,它将仅处理第 2 行和第 3 行。我想要的是在超过 1 个测试用例的情况下,我必须处理第 4、第 5 ... 行。目前我正在检查 if(i == 0) -> 而不是这个,有什么方法可以检查每一行吗?
-
你的预期输出是什么?
-
用预期的输出修改了问题。在 testcase1 的情况下,它会打印 结果是:yes 结果是:no (在数组 [6,7,8,9] -> 6 存在并且 10 不存在.. 在 testcase 2 的情况下,它将打印结果是:是(在数组 [7,8,14] -> 7 存在)
-
是否需要检查输入文件中的错误?例如缺少行?没有足够的数组值的行?
标签: python python-3.x filereader