Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-25 Thread Terry Hancock
On Saturday 23 April 2005 02:43 am, Mage wrote:
 Scott David Daniels wrote:
  See, the body of your anonymous function just looks for the current
  value of n when it is _invoked_, not when it is _defined_.
 
 The lambda functions was an unclear part of the tutorial I read.
 Should I use them? Are they pythonic?
 As far I see they are good only for type less a bit.

Lambda has two main uses, IMHO:

1) You need to create a whole lot of functions which all follow a certain
pattern, but must evaluate late (i.e. the arguments will be added later,
so you can't just compute the result instead). This is basically the 
case the OP presented with his list of increasing powers.  You can, of
course, use named functions for each, but it may become impractical.

2) You are going to apply the same (arbitrary) function to many sets of 
arguments.
This argues for taking a function as an argument.  Python Imaging Library
does this with the 'point' method, for example.

Frequently you will run into a trivial case such as:

def squared_plus_one(x):
 return x**2 + 1

result_ob = source_ob(transform=squared_plus_one)

or something like that.  It gets pretty silly to clutter up your code with such
trivial functions, and lambda gives you a neat way to simply define the function
for the moment you need it and throw it away:

result_ob = source_ob(transform=lambda x: x**2 + 1)

Note that in this case, the expression is probably the clearest way to document
the function (clearer than the function name, IMHO).

So, yeah, they have some real uses.  But you can live without them most
of the time.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread Terry Hancock
On Friday 22 April 2005 06:44 pm, Scott David Daniels wrote:
 Terry Hancock wrote:
  On Friday 22 April 2005 05:18 pm, [EMAIL PROTECTED] wrote:
  
  Perhaps you don't know how to call such functions?  E.g.:
  a=[ lambda t: t**n for n in range(4) ]
 a[2](3)
  27
 
 Didn't you notice this was a funny value?

Nope. Wasn't paying attention. ;-)

Just copied the code from the OP.

 Perhaps you mean:
   a = [lambda t, n=n: t**n for n in range(4)]

This is of course what he should've written, and/or what I
should've corrected it to, thank you. 

Cheers,
Terry


--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread Terry Hancock
On Friday 22 April 2005 05:18 pm, [EMAIL PROTECTED] wrote:
 Thanx for your replies.
 
 I'm looking for array of functions.
 Something like a=[ sin(x) , cos(x) ]

You had a list of lambda functions in your first post and in the
subject line still. How is that not what you wanted?

If you want an *answer*, you need to ask a *question*. 

Perhaps you don't know how to call such functions?  E.g.:

a=[ lambda t: t**n for n in range(4) ]

 a[2](3)
27

If you want to see *names* for the functions, you have two
choices: either used named functions, 

def unity(t): return 1
def identity(t): return t
def square(t): return t**2
def cube(t): return t**3
a = [unity, identity, square, cube]

 a
[function unity at 0x401e609c, function identity at 0x401e6b54,
function square at 0x401e6b8c, function cube at 0x401e6ca4]

or replace the list with a dictionary, e.g.:

a = dict([('t**%d' % n, lambda t: t**n) for n in range(4)])

 a
{'t**0': function lambda at 0x401e6bc4, 't**1': function lambda at 
0x401e6bfc, 
't**2': function lambda at 0x401e6c34, 't**3': function lambda at 
0x401e6c6c}
 a.keys()
['t**0', 't**1', 't**2', 't**3']
 a['t**3'](4)
64



--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread El Pitonero
Bengt Richter wrote:
 I still don't know what you are asking for, but here is a toy,
 ...
 But why not spend some time with the tutorials, so have a few more
cards in your deck
 before you try to play for real? ;-)

Communication problem.

All he wanted is automatic evaluation a la spreadsheet application.
Just like in Microsoft Excel. That's all.

There are many ways for implementing the requested feature. Here are
two:

(1) Push model: use event listeners. Register dependent quantities as
event listeners of independent quantities. When an independent quantity
is modified, fire off the event and update the dependent quantities.
Excel uses the push model.

(2) Pull model: lazy evaluation. Have some flag on whether an
independent quantity has been changed. When evaluating a dependent
quantity, survey its independent quantities recursively, and update the
cached copies whereever necessary.

Of course, combination of the two approaches is possible.

For Python, metaclasses and/or decorators and/or properties may help.

But functional languages are a more natural territory.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread Bill Mill
On 22 Apr 2005 14:41:45 -0700, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 I was thinking about something like the following;
 
  a=[ t**n for n in range(4) ]
 Traceback (most recent call last):
  File stdin, line 1, in ?
 NameError: name 't' is not defined
 
 
 or
 
  a=[ lambda t: t**n for n in range(4) ]
  t=2
  a
 [function lambda at 0x403dcc6c, function lambda at 0x403dcca4,
 function lambda at 0x403dccdc, function lambda at 0x403dcd14]
  t=3
  a
 [function lambda at 0x403dcc6c, function lambda at 0x403dcca4,
 function lambda at 0x403dccdc, function lambda at 0x403dcd14]
 
 

Well, everybody else took away your lambda (greedy people!) but I'm
here to say that it doesn't *have* to go away. I didn't think this
would be possible, but it is:

 t = 2
 [(lambda n: t**n)(n) for n in range(4)]
[1, 2, 4, 8]
 t = 3
 [(lambda n: t**n)(n) for n in range(4)]
[1, 3, 9, 27]

I just thought that was kinda neat. If you wanted to obfuscate some
python, this would be an awesome trick - hide the value of t somewhere
early in the function then pull a variation of this out later.

Peace
Bill Mill
bill.mill at gmail.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread mehmetmutigozel

Thanx.

It just popped in my mind.

in 3d programming there are transformation matrices like
a=[[cos(x),sin(x),0],[-sin(x),cos(x),0],[0,0,1]]
it is a 3x3 matrix. never changes during program.

it can be defined like
 def transmat(x):
...   dummy=[[0,0,0],[0,0,0],[0,0,0]]
...   dummy[0][0]=cos(x)
...   ~~
...   return dummy

a=transmat(1.0)

it is usual way for this.

i wonder if there is an automatic way to make that without calling a
function.

an automatic way that depends on changing the value of x. as each time
x=something used the whole matrix changes automaticly.

or maybe i am just dreaming. :)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread Bengt Richter
On 22 Apr 2005 15:18:53 -0700, [EMAIL PROTECTED] wrote:

Thanx for your replies.

I'm looking for array of functions.
Something like a=[ sin(x) , cos(x) ]

 x=0.0
 a
[0, 1]
 x=1.0
 a
...

of course it can be made by
 def cratearray(x):
...   
...   return a
a=createarray(1.0)

but this isn't what i am asking for. something automized.

I still don't know what you are asking for, but here is a toy,
whose code you will be able to improve on later, but at least
provides concrete behavior that you can comment on, and maybe
explain what you are really asking for.

  class FunArray(object):
 ... def __init__(self, *funs):
 ... self.__dict__['_funs'] = funs
 ... self.__dict__['_names'] = []
 ... vars
 ... def __getattribute__(self, attr):
 ... if attr.startswith('_') or hasattr(type(self), attr):
 ... return object.__getattribute__(self, attr)
 ... v = vars(self).get(attr)
 ... if v is None: return ['%r is not set'%attr]
 ... return [f(v) for f in self._funs]
 ... def __setattr__(self, attr, v):
 ... if attr.startswith('_'): raise AttributeError, attr
 ... else:
 ... if attr in self._names: self._names.remove(attr)
 ... self._names.append(attr)
 ... self.__dict__[attr] = v
 ... def __repr__(self):
 ... last = self._names and self._names[-1] or '??'
 ... d= vars(self)
 ... return 'FunArray names: %s\n  %r = %s'% (
 ... ', '.join(['%s=%r'%(k, d[k]) for k in self._names]),
 ... last, repr(getattr(self, last)))
 ...
  from math import sin, cos, pi
  a = FunArray(sin, cos)
  a.x = 0.0
  a
 FunArray names: x=0.0
   'x' = [0.0, 1.0]
  a.x
 [0.0, 1.0]
  a.y = 1.0
  a.y
 [0.8414709848078965, 0.54030230586813977]
  a
 FunArray names: x=0.0, y=1.0
   'y' = [0.8414709848078965, 0.54030230586813977]
  a.z = pi/3
  a
 FunArray names: x=0.0, y=1.0, z=1.0471975511965976
   'z' = [0.8660254037844386, 0.50011]
  a.x = pi/6
  a
 FunArray names: y=1.0, z=1.0471975511965976, x=0.52359877559829882
   'x' = [0.49994, 0.86602540378443871]


If you just want an interactive calculator that acts according to your taste,
you can program one to prompt and read (use raw_input, not input BTW) what you
type in and calculate and print whatever form of result you'd like. See the cmd
module for one way not to reinvent some wheels.

But why not spend some time with the tutorials, so have a few more cards in 
your deck
before you try to play for real? ;-)

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread Mage
Scott David Daniels wrote:



 See, the body of your anonymous function just looks for the current
 value of n when it is _invoked_, not when it is _defined_.

The lambda functions was an unclear part of the tutorial I read.
Should I use them? Are they pythonic?
As far I see they are good only for type less a bit.

   Mage


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread tiissa
[EMAIL PROTECTED] wrote:
i wonder if there is an automatic way to make that without calling a
function.
You mean without _explicitely_ calling a function.
May I inquire why you need to write f instead of f(x)?
an automatic way that depends on changing the value of x. as each time
x=something used the whole matrix changes automaticly.
As pointed out by El Pitonero property can be your friend:
  class A(object):
 ... def get_v(self):
 ... return [1,x]
 ... v=property(get_v)
 ...
  a=A()
  x=0
  a.v
 [1, 0]
  x=2
  a.v
 [1, 2]
 
However, you will calculate your matrix each time you will access it 
(and I find it ugly to use a global variable this way).

You can however build it the other way round:
  class B(object):
 ... def __init__(self):
 ... self.v=[1,0]
 ... self.x=0
 ... def calc_v(self):
 ... self.v[1]=self.__x
 ... def set_x(self,x):
 ... self.__x=x
 ... self.calc_v()
 ... def get_x(self):
 ... return self.__x
 ... x=property(get_x, set_x)
 ...
  b=B()
  b.v
 [1, 0]
  b.x=2
  b.v
 [1, 2]
 
This time, calculations only occur when you change the value of x.
--
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread Harald Massa
Mage [EMAIL PROTECTED] wrote in news:mailman.2339.1114242211.1799.python-

 The lambda functions was an unclear part of the tutorial I read.
 Should I use them? Are they pythonic?
 As far I see they are good only for type less a bit.

And to obfusicate code. lambda is evil, do not play with it.

Harald
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread Scott David Daniels
Mage wrote:
Scott David Daniels wrote:
See, the body of your anonymous function just looks for the current
value of n when it is _invoked_, not when it is _defined_.
The lambda functions was an unclear part of the tutorial I read.
Should I use them? Are they pythonic?
As far I see they are good only for type less a bit.
As for most python features which are not dead obvious, you should
only use them where they they make the code clearer than it would be
without the use of that feature.  In this case, I was responding to
a particular use of lambda which, in fact, had a flaw that made the
code do something different from what it looked like it was doing.
I felt the distinction was clearer in the lambda form than it would
have been with def-style function definitions.  One of the reasons
the distinction came out was that there was no confusing naming of
what this function means, only program structure.  In a real program
that is a hindrance.  In the case of pointing out a flaw, it makes
differences between two versions of some code more obvious.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread Bengt Richter
On 22 Apr 2005 20:45:55 -0700, El Pitonero [EMAIL PROTECTED] wrote:

Bengt Richter wrote:
 I still don't know what you are asking for, but here is a toy,
 ...
 But why not spend some time with the tutorials, so have a few more
cards in your deck
 before you try to play for real? ;-)

Communication problem.
Indeed.


All he wanted is automatic evaluation a la spreadsheet application.
Just like in Microsoft Excel. That's all.

There are many ways for implementing the requested feature. Here are
two:

(1) Push model: use event listeners. Register dependent quantities as
event listeners of independent quantities. When an independent quantity
is modified, fire off the event and update the dependent quantities.
Excel uses the push model.
This is essentially what I was demonstrating with the namespace of FunArray,
showing object attribute namespace access as perhaps _the_ 'listening hook
of Python -- which properties and overriding base class methods with
subclass methods etc. etc. all depend on.

FunArray 'listens' for named spreadsheet cell assignments to its namespace,
and it listens for a repr access to the spreadsheet as a whole, presenting
its status in terms of cell names and the formula value of the last cell 
entered.

Not conventional, but I wanted to stay as close to the OP's proposed
example interactive log (if that was what it was, which apparently it wasn't ;-)

This does also demonstrate that if you want to listen for apparent
assignments to bare names, AFAIK there is no way without byte code hackery
or using a trace hook, or just doing your own eval-print loop,
which is why I suggested the cmd module as a start.

of course, you could mess with displayhook to get what the OP originally
appeared to be asking for. E.g., this toy produces an interactive log
much like the OP specified:

  class DH(object):
 ... def __init__(self):
 ... import math
 ... self.env = vars(math)
 ... self.env.update(vars(__builtins__))
 ... def evalstrex(self, s):
 ... for name in compile(s,'','eval').co_names:
 ... if type(self.env[name]) == str:
 ... self.env[name] = self.evalstrex(self.env[name])
 ... return eval(s, self.env)
 ... def __call__(self, o):
 ... if type(o)==str:
 ... self.env.update(globals())
 ... o = self.evalstrex(o)
 ... sys.__displayhook__(o)
 ...
  import sys
  sys.displayhook = DH()

Other than the quotes around the formula,

  a = '[sin(x), cos(x)]'
  x=0.0
  a
 [0.0, 1.0]
  x=1.0
  a
 [0.8414709848078965, 0.54030230586813977]

looks a lot like

 
 I'm looking for array of functions.
 Something like a=[ sin(x) , cos(x) ]

  x=0.0
  a
 [0, 1]
  x=1.0
  a
 ...

 of course it can be made by
  def cratearray(x):
 ...   
 ...   return a
 a=createarray(1.0)

 but this isn't what i am asking for. something automized.


Of course, this is not what the OP _really_ wanted ;-)

But it's kind of fun. Anything you type in quotes is evaluated
using available global bindings plus the ones in the math module
and __builtins__, and it's recursive, so if a name in the quoted
formula refers to another string (which must be a valid expression),
that is evaluated, and so on. This is pull based on interactive
display trigger ;-)

  x='pi/6'
  a
 [0.49994, 0.86602540378443871]

  x='pi/6'
  a
 [0.49994, 0.86602540378443871]
  x = 'pi/y'
  y=6
  a
 [0.49994, 0.86602540378443871]
  y=3
  a
 [0.8660254037844386, 0.50011]

The display hook passes through non-strings, so you can box a string formula to 
see it:

  [a]
 ['[sin(x), cos(x)]']
  [x]
 ['pi/y']
  [y]
 [3]


You could specify your spread sheet:

  a1,a2,a3=100,200,'sum([a1,a2])'
  a1,a2,a3
 (100, 200, 'sum([a1,a2])')
  a1
 100
  a2
 200
  a3
 300

;-)


(2) Pull model: lazy evaluation. Have some flag on whether an
independent quantity has been changed. When evaluating a dependent
quantity, survey its independent quantities recursively, and update the
cached copies whereever necessary.

Of course, combination of the two approaches is possible.

For Python, metaclasses and/or decorators and/or properties may help.

But functional languages are a more natural territory.


Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list