samedi 23 janvier 2021

Python If/Else Logic with File I/O

I have a program that reads in 5 files, performs a "two sum" algorithm over the arrays in the file, and outputs to a new file if there's a sum of two numbers that matches the target.

I've got the logic to handle everything except if there's no match. If there's no match I need to write "No" to the output file. If I just add else: f.write("No") after the second if then it'll write "No" for every pass that it's not a match. I need it write "No" ONCE at the end of the processing, after it hasn't found a match.

Read 5 "in" files

inPrefix = "in"
outPrefix = "out"
for i in range(1, 6):
    inFile = inPrefix + str(i) + ".txt"
    with open(inFile, 'r') as f:
        fileLines = f.readlines()
        target = fileLines[1]
        arr = fileLines[2]

Output 5 "out" files

    outFile = outPrefix + str(i) + ".txt"
    with open(outFile, 'a') as f:
        f.write(target)
        f.write(arr)
        target = int(target)
        num_arr = [int(j) for j in arr.split()]

        for a in range(len(num_arr)):
            for b in range(a, len(num_arr)):
                curr = num_arr[a] + num_arr[b]
                if num_arr[a]*2 == target:
                    a = str(num_arr[a])
                    target = str(target)
                    answer = "{}+{}={}".format(a,a,target)
                    f.write("Yes")
                    f.write("\n")
                    f.write(answer)
                    break
                if curr == target:
                    a = str(num_arr[a])
                    b = str(num_arr[b])
                    target = str(target)
                    answer = "{}+{}={}".format(a,b,target)
                    f.write("Yes")
                    f.write("\n")
                    f.write(answer)
                    break
    f.close()

Aucun commentaire:

Enregistrer un commentaire