Applications/examples of some advanced Py features, please !

Terry Reedy tjreedy at udel.edu
Sat Jan 4 13:26:31 EST 2003


"Az Tech" <aztech1200 at yahoo.com> wrote in message
news:5a969143.0301040712.4cd2ad10 at posting.google.com...

> Can anyone please give some examples / applications of the use of
the
> following advanced (advanced to me, at least :-) features of Python
:

> 2. nested functions - a little info was given by Danny in reply to
my
> earlier post on local-static variables, but I would like more.

There are at least two quite different uses for nested functions:

A. Create and return a function!  Simple example:

def adder(n):
  def _(m): return m+n
  return _

or, more succintly (preference being a matter of taste and programming
religion).

def adder(n): return lambda m: m+n

B. Implement a recursive algorithm.  Nesting may be useful for at
least two reasons:

B1. There may be some initial calculation that only needs to be done
once and may need to be done only once (and never again).  Example a:
checking the validity of external input.  Once this is done, you know
that your recursive calls will be made with valid values that do not
need to be checked.  Example b: calculating the initial value of an
internal data structure.

B2. Recursion may (and often does) require an additional parameter
that users do not need to know about, let alone be required to enter
the initial value of.  In other words, f(x) may be implemented as g(x,
c0), where c0 is the initial value of the addition param.

Example: list all ways to partition positive count n as the sum of k
positive counts:

def part(n0, k0):
  if not 1 <= k0 <= n0: raise ValueError, "k must be in range [1,n]"
  # only needs to be done once
  result = []
  worklist = [0]*k0
  # must be done only once
  def _part(n, k, previous,):
    if k == 1:
      worklist[0] = n
      result.append(tuple(worklist))
    else:
      k1 = k-1
      for p in range(min(previous, n - k1), (n-1)/k, -1):
        worklist[k1] = p
        _part(n-p, k1, p)
  _part(n0, k0, n0)
  # note 3rd param which is initially n but generally not thereafter
  # making function user enter this twice would be error-prone
nuisance,
  # especially if argument for n is an expression
  return result

>>> part(6,2)
[(1, 5), (2, 4), (3, 3)]
>>> part(6,3)
[(1, 1, 4), (1, 2, 3), (2, 2, 2)]
>>> part(6,4)
[(1, 1, 1, 3), (1, 1, 2, 2)]

Terry J. Reedy






More information about the Python-list mailing list