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
185 views
in Technique[技术] by (71.8m points)

Python: write function return value to output file

I have 5 input files. I'm reading the targets & arrays from the 2nd & 3rd lines. I have 2sum function. I need to output the function's returned value(s) and output them to 5 output files.

I know my functions correct. I print it out just fine. I know I'm reading 5 input files & creating & writing to 5 output files.

What I can't figure out is how to write my return value(s) from the twoSum function INTO the output function.

def twoSum(arr, target):
    for i in range(len(arr)):
        for j in range(i, len(arr)):
            curr = arr[i] + arr[j]
            if arr[i]*2 == target:
                return [i, i]
                return answer
            if curr == target:
                return [i, j]

Read 5 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]

how do i get write twoSum's value to output file?

???????

Output to 5 files

    outFile = outPrefix + str(i) + ".txt"
    with open(outFile, 'a') as f:
        f.write(target) #just a test to make sure I'm writing successfully
        f.write(arr)    #just a test to make sure I'm writing successfully
question from:https://stackoverflow.com/questions/65863765/python-write-function-return-value-to-output-file

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

1 Answer

0 votes
by (71.8m points)

Two things that come to mind:

  1. open the file in wt mode (Write Text).
  2. processedOutput appears to be a list. When you write to a file, you need write a string. Are you wanting a CSV style output of those values ? or just a line of spaced out values ? The simplest way here, would be something like: " ".join(processedOutput). That will separate all the items in your processedOut list by a string.

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

...