[Edu-sig] Factory functions: synthesizing top-level names

Andre Roberge andre.roberge at gmail.com
Thu May 27 04:21:54 CEST 2010


On Wed, May 26, 2010 at 4:58 PM, kirby urner <kirby.urner at gmail.com> wrote:

> Creating Top-Level names root0, root1, root2... rootN
>
> SNIP


>
> What they'd like to do is this:  for 2nd, 3rd, 4th,
> 5th etc. root of a number, have the functions
> root2, root3, root4... up to root10 routinely available,
> perhaps in a module called roots or radicals.
>
> >>> import radicals as r
> >>> r.root3 ( 2.0 / 3.0 )
> 0.8735804647362989
>
> So how might we generate root0... root10 in a
> factory function, such that these function names
> become top level within their generating and/or
> defining module?
>
> True, we could individually define these functions
> per the example below, but what is a clever way
> of generating rootN in principle, such as root2012,
> taking 2012 as an argument.
>
>
Ok, here's my solution:

>>> def make_root(i):
...    def _root(x):
...         return pow(x, 1.0/i)
...    return _root
...
>>> for i in range(1, 11):
...     locals()['root' + str(i)] = make_root(i)
...
>>> root2(4)
2.0
>>> root4(64)
2.8284271247461903
>>> root6(64)
2.0

Cheers,
André



> Hints:
>
> For root2, you might take an obvious shortcut:
>
> from math import sqrt as root2
>
> For root3, consider the following:
>
> def root3 (x):  return pow( x, 1.0/3.0 )
>
> In general:
>
> def rootN (x):  return pow( x, 1.0/N)
>
> Rationale for this exercise:
>
> Students often want a way to factory-produce
> new names at the top level, from within a contained
> scope (such as from within a function).
>
> These top level names may be of data, functions or
> whatever arbitrary objects.  The production process
> often involves synthesizing new names on the fly,
> as strings.  Strings are "right side" objects, usually
> assigned names, but not themselves names of
> anything.
>
> By what magic might we turn a string object into
> a top-level name:  that is the question this lesson
> addresses.
>
>
> _______________________________________________
> Edu-sig mailing list
> Edu-sig at python.org
> http://mail.python.org/mailman/listinfo/edu-sig
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20100526/1dc6f7a0/attachment.html>


More information about the Edu-sig mailing list