473,804 Members | 2,126 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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>]


is something like that possible? Will you give me advice about that?

Jul 19 '05
17 2007
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.

Jul 19 '05 #11
On Friday 22 April 2005 06:44 pm, Scott David Daniels wrote:
Terry Hancock wrote:
On Friday 22 April 2005 05:18 pm, me************* @gmail.com 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 anansispacework s.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 19 '05 #12
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
Jul 19 '05 #13
me************* @gmail.com 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.
Jul 19 '05 #14
Mage <ma**@mage.hu > wrote in news:mailman.23 39.1114242211.1 799.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
Jul 19 '05 #15
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
Sc***********@A cm.Org
Jul 19 '05 #16
On 22 Apr 2005 20:45:55 -0700, "El Pitonero" <pi******@gmail .com> 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 morecards in your deck
before you try to play for real? ;-)


Communicatio n 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 "spreadshee t cell" assignments to its namespace,
and it "listens" for a repr access to the "spreadshee t" 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(__builtin s__))
... def evalstrex(self, s):
... for name in compile(s,'','e val').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.__displayho ok__(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.8414709848078 965, 0.5403023058681 3977]

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.4999999999999 9994, 0.8660254037844 3871]
x='pi/6'
a [0.4999999999999 9994, 0.8660254037844 3871] x = 'pi/y'
y=6
a [0.4999999999999 9994, 0.8660254037844 3871] y=3
a [0.8660254037844 386, 0.5000000000000 0011]

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,20 0,'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
Jul 19 '05 #17
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_on e(x):
return x**2 + 1

result_ob = source_ob(trans form=squared_pl us_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(trans form=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 anansispacework s.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 19 '05 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3041
by: Peter Barth | last post by:
Hi, trying to mix lambda expresions and list comprehension doesn't seem to work. --- >>> (2) 11 >>> (2) 11 --- I expected the second expression to return 6.
8
2630
by: Ian McMeans | last post by:
I was bitten by a bug today that depended on how lambda works. It took me quite a while to realize what was going on. First, I made multiple lambda functions inside a loop, each of which depended on the current loop variable. >>> a = >>> for index in range(5): a.append(lambda: index)
9
1637
by: Darabos Daniel | last post by:
Hi! I was doing something like this: >>> def p( x ): .... print x .... >>> l = >>> for i in range( 5 ): .... l.append( lambda: p( i ) )
1
374
by: Xin Wang | last post by:
Some c++ guru said c++ is hard to learn but easy to use. Is python easy for both aspect? I found lot's of confused in coding. #code from Tkinter import * def on_click(m): print m def lamb_on_click(m):
4
1635
by: markscottwright | last post by:
Just for the hell of it, I've been going through the old Scheme-based textbook "Structure and Interpretation of Computer Programs" and seeing what I can and can't do with python. I'm trying to create a function that returns the function (not the results of the function, but a function object) that results from applying function f to it's (single) argument N times. For example, if you have "def sq(x): return x*x", then repeated(sq, 2)(2)...
181
8932
by: Tom Anderson | last post by:
Comrades, During our current discussion of the fate of functional constructs in python, someone brought up Guido's bull on the matter: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 He says he's going to dispose of map, filter, reduce and lambda. He's going to give us product, any and all, though, which is nice of him.
5
2523
by: Max Rybinsky | last post by:
Hello! Please take a look at the example. >>> a = # Just a list of tuples >>> a Now i want to get a list of functions x*y/n, for each (x, y) in a:
8
339
by: rubbishemail | last post by:
Hello, I need your help understanding lambda (and doing it a better way without). f = lambda x : x*x # this is a list of functions
4
1009
by: wyleu | last post by:
I'm trying to supply parameters to a function that is called at a later time as in the code below: llist = for item in range(5): llist.append(lambda: func(item)) def func(item): print item
0
9711
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9593
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9169
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7633
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.