kk.lau
kk.lau

Reputation: 47

Using lambdas in a function within a function

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?

Upvotes: 0

Views: 129

Answers (1)

steveha
steveha

Reputation: 76715

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 None for transform. Then check to see if transform is None. If it is not, then try to call it, passing the current line, and collecting the output as the new current line. If transform is None then you just write the current line unchanged.

Alternatively, you could declare this trivial function:

def nop(x):
    return x

And then specify that the default for argument transform is the function nop. Which is better, to test for None and 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 for None avoids 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 argument transform is.

Upvotes: 3

Related Questions