0

The title is a little weird, but I don't know exactly how this is called, so plz forgive me with the abstract title....

I've found a code like this online:

def lcs(xstr, ystr):
    """
    >>> lcs('thisisatest', 'testing123testing')
    'tsitest'
    """
    if not xstr or not ystr:
        return ""
    x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:]
    if x == y:
        return x + lcs(xs, ys)
    else:
        return max(lcs(xstr, ys), lcs(xs, ystr), key=len)

I am new to python, and I don't understand how you can call lcs(xs, ys) in

return x + lcs(xs, ys)

To my understanding, lcs() is not yet fully defined, and I'm confused how you can call a function of itself inside itself....

Also, I don't know what key = len is doing in

max(lcs(xstr, ys), lcs(xs, ystr), key=len)

I know how max( 1st, 2nd ) works, but I don't know what the third parameter is doing. What does "key" mean, and why is "len" used as a value of "key"?

smci
  • 32,567
  • 20
  • 113
  • 146
Eric Kim
  • 2,493
  • 6
  • 33
  • 69
  • 1
    https://en.wikipedia.org/wiki/Recursion_(computer_science) – wwii Oct 26 '17 at 22:58
  • You are correct that when you *define* the function, the function itself isn't defined. however, the function *is defined* when you call it, so there won't be a `NameError`. – juanpa.arrivillaga Oct 26 '17 at 22:59

1 Answers1

4

This is called recursion. The body of the function isn't evaluated at all until you call it. Think of lcs in the body as just a name; when you call the function, Python will apply the same lookup rules it applies to any name to see what it refers to; typically* it refers to the same function.


*Typically, because you can break a recursive function by playing some games with the names.

def foo():
    print("hi")
    foo()

g = foo
def foo():
    print("new function")

If you call g(), it will output

hi
new function

instead of print an infinite stream of lines containing hi. (Well, almost infinite; eventually you'll get a RuntimeError because Python caps the size of the call stack.)

chepner
  • 497,756
  • 71
  • 530
  • 681