Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Reply

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...