I used recursion a while ago (in JavaScript) using strings.  I don't
have the code handy, but I do recall the context.  I needed to find
the <form> element that was the parent/grandparent/great-grand-parent
of the current element.  I didn't know how many levels I needed to go
up.

To paraphrase it in python:

def getParentForm(element):
    if element.parent == document:
        return None
    if type(element.parent) == "FORM":
        return element.parent
    return getParentForm(element.parent)

Naturally, this is more terse in python than it was in JS!

This is a safer form of recursion, as it has a limit to the number of
times it is called.  This is not a limit placed by my coding, but by
the fact that unless the HTML DOM on which it is operating has an
infinite number of nested elements, of which this is the last (!),
then it will at some stage return either the element that is a form,
or None.  And the hope is that the scripting language can handle
nested calls of at least as many nests as the HTML parser. :)

Matt.
(I'm new to this list, but I'm planning on teaching python to a
final-year-of-high-school class in about 8 weeks time)

On 09/02/07, kirby urner <[EMAIL PROTECTED]> wrote:
>
>
> Andy:
> >  But they don't have any clue that there's a call stack involved, or that
> > someday this could get them in trouble.  I shudder to think about the
> > blank looks that I will get if I try to explain why it could be a problem.
>
>
> I'd praise those stumbling on recursion, use the opportunity to talk about
> it more specifically, and about how some languages are based on it rather
> intensively (others not so much).
>
> Greatest Common Divisor may be written both ways:
>
> def gcd(a,b):
>    while b:
>       a, b = b, a % b
>    return a
>
> or:
>
> def gcd(a,b):
>    if b:
>       return gcd(b, a % b)
>    return a
>
> But of course if your 10th graders are pathologically math phobic,
> like so many of their college peers, you'll want to eschew any
> such examples and deal purely with strings.
>
> Kirby
>
> _______________________________________________
> Edu-sig mailing list
> [email protected]
> http://mail.python.org/mailman/listinfo/edu-sig
>
>


-- 
Matthew Schinckel <[EMAIL PROTECTED]>

The Feynman Problem-Solving Algorithm:
  (1) write down the problem;
  (2) think very hard;
  (3) write down the answer.
_______________________________________________
Edu-sig mailing list
[email protected]
http://mail.python.org/mailman/listinfo/edu-sig

Reply via email to