开发者

Add one to a function call in python

What does the last line, return 1 + .... do ? How can you return 1 plus a function call?

Below is the assignments text:

These functions recursively count the number of instances of the key in the target string

def countSubStringMatchRecursive(target, key):
    curre开发者_开发问答ntPosition = find(target, key)
    if find(target, key) == -1:
        return 0
    else:
        return 1 + countSubStringMatchRecursive(target[currentPosition+1:], key) 


The last line isn't returning "1 plus a function call", it is returning 1 + the return value of the function, which is either 0 or 1 depending on whether the condition has been met.

It is recursive, in that the return value from the function call will be 1 + the return value of another function call -- again, and again, and again, until find(target, key) == -1.

Think of it more like:

return 1 + ( 1 + (1 + (1 + (0))))


Its best to think of this from the end case. Lets say you have 3 possible matches. The calls would like this,

countSubStringMatchRecursive(target, key)

  (The find operation is not -1, so call again)
  1 + countSubStringMatchRecursive(target, key)

    (The find operation is not -1, so call again)
    1 + countSubStringMatchRecursive(target, key)

      In this end case, the find operation is -1, so this function returns a 0.

    Return value at this level is now 1 + 0 = 1

  Return value at this level is now 1 + 1 = 2

 Return value at the topmost level is now 1 + 2 = 3

So as you can see, the 1+ function call is basically a way to keep track of the count.


The code that you showed does this:

currentPosition = find(target, key)
if find(target, key) == -1:

when it should be doing this:

currentPosition = find(target, key)
if currentPosition == -1:

If your teacher actually wrote that code, it's time to change schools!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜