简体   繁体   中英

Python script for reading from file and display an output

Wrote a python script that reads from a file input.txt

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,8,14]

The 1st line in the file indicates number of test cases. In this example, we have 2 test cases. Each test case have 2 lines to process - in which first line indicates size of 1st array and size of 2nd array. 2nd line indicates the both array details.

ie, In above example, line 2 indicates size of 1st array and 2nd array for testcase1. line 3 indicates 2 arrays in mentioned sizes for testcase1.line 4 indicates size of 1st array and 2nd array for testcase2. line 5 indicates 2 arrays in mentioned sizes for testcase2.

I need to check whether the elements of 1st array is present in the 2nd one for each test cases. I wrote below program, but that will execute only for 1 test case(ie, I'm checking 2nd and 3rd line manually by giving the check i == 0)

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()

Can anyone please help me in this?

output will be like

The result is : yes
The result is : no
The result is : yes

I would read the file line by line and process.

# 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

The function int(x) will raise ValueError when input is bad.

Checking the length of the lists allows you to make sure you get the expected number of values on each line.

If the file runs out of lines, readline() will return an empty string which results in a list with length 0 when you split and should fail the length checks.

You can use try, catch to write code to handle the errors such as ValueError from int().

Try this

first_array=[1,2,3]
sec_array=[4,5,3]
print(any(i in sec_array for i in first_array)) # prints True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM