问题描述
编写了一个从文件 input.txt 中读取的 python 脚本
input.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,14]
文件中的第一行表示测试用例的数量。在这个例子中,我们有 2 个测试用例。 每个测试用例有 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,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
解决方法
我会逐行读取文件并处理。
# read a line and convert to int() for num_cases.
for i in range(0,2 * num_cases,2):
# read a line for split_list
# check length of split_list
# read a line for list values all_nums
# check length of all_nums to be equal to sum of split_list
# split the list into arr1 and arr2.
# You can use slicing notation.
# For example:
# arr[:5] are the first 5 elements of arr. i.e. indexes 0,1,2,3,4
# arr[:-5] are the last 5 elements of arr. i.e. indexes len(arr) - 5,...,len(arr) - 1
# arr[5:] are elements 5 and on from arr. i.e. indexes 5,6,...
for value in arr1:
if value in arr2:
# output
else:
# output
当输入错误时,函数 int(x) 将引发 ValueError。
检查列表的长度可以确保您在每行上获得预期数量的值。
如果文件用完行,readline() 将返回一个空字符串,当您拆分时,该字符串将导致长度为 0 的列表,并且长度检查应失败。
可以使用try、catch编写代码来处理int()中的ValueError等错误。
,试试这个
first_array=[1,3]
sec_array=[4,5,3]
print(any(i in sec_array for i in first_array)) # prints True