Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

if statement - 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("
")
                    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("
")
                    f.write(answer)
                    break
    f.close()
question from:https://stackoverflow.com/questions/65867185/python-if-else-logic-with-file-i-o

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Initialize a variable -- let's call it wrote_yes -- to False at the top of the code.

Anytime you write "Yes" to the file, set that variable to True.

When you reach the end of all the processing, check that variable. If it's still False, then you never wrote "Yes", so now you can write "No".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...