I have an assignment where I’m asked to modify some code. The original function is this:
def selectivelyCopy(inputFile,outputFile,predicate):
linesCopied = 0
for line in inputFile:
if predicate(line):#test the line with the predicate
outputFile.write(line)
linesCopied+=1
inputFile.close()
return linesCopied
Now I am suppose to add the parameter transform, a function that takes in as its parameter a string, and returns a string according to the transformation specified by the user. If transform is omitted from the function call, lines from the input file are written unchanged.
Here is what I have so far:
def selectivelyCopy2(inputFile,outputFile,predicate, transform):
def transform(x = lambda x: x):
return(x)
linesCopied = 0
for line in inputFile:
if predicate(line): #test the line with the predicate
outputFile.write(line)
linesCopied+=1
inputFile.close()
return linesCopied
I’m not sure where to proceed from here. I think I’m suppose to read the input file line, but write the transformed line…or something?
Now I am suppose to add the parameter transform, a function that takes in as its parameter a string, and returns a string according to the transformation specified by the user. If transform is omitted from the function call, lines from the input file are written unchanged.
That sounds to me very simple: you are supposed to accept a function argument called
transform, and if it is supplied, you call it. If it is not supplied, you either don’t call it, or else you call a trivial function that returns its input unchanged.I suggest that you use a default argument of
Nonefortransform. Then check to see iftransform is None. If it is not, then try to call it, passing the current line, and collecting the output as the new current line. Iftransform is Nonethen you just write the current line unchanged.Alternatively, you could declare this trivial function:
And then specify that the default for argument
transformis the functionnop. Which is better, to test forNoneand call nothing, or to have a sensible no-operation default function and always call it? I think this is mostly a matter of personal preference. The test forNoneavoids the overhead of a function call, so it is probably slightly faster, but it probably isn’t a big deal either way.There is no reason to declare a private function named
transform, and by doing that you are making it impossible to check what the argumenttransformis.